Python numpy.hypot() Examples

The following are 30 code examples for showing how to use numpy.hypot(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: recruit   Author: Frank-qlu   File: test_ufunc.py    License: Apache License 2.0 6 votes vote down vote up
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,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 2
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
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 3
Project: vnpy_crypto   Author: birforce   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
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 4
Project: sea_ice_drift   Author: nansencenter   File: pmlib.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_hessian(ccm, hes_norm=True, hes_smth=False, **kwargs):
    """ Find Hessian of the input cross correlation matrix <ccm>

    Parameters
    ----------
    ccm : 2D numpy array, cross-correlation matrix
    hes_norm : bool, normalize Hessian by AVG and STD?
    hes_smth : bool, smooth Hessian?

    """
    if hes_smth:
        ccm2 = nd.filters.gaussian_filter(ccm, 1)
    else:
        ccm2 = ccm
    # Jacobian components
    dcc_dy, dcc_dx = np.gradient(ccm2)
    # Hessian components
    d2cc_dx2 = np.gradient(dcc_dx)[1]
    d2cc_dy2 = np.gradient(dcc_dy)[0]
    hes = np.hypot(d2cc_dx2, d2cc_dy2)
    if hes_norm:
        hes = (hes - np.median(hes)) / np.std(hes)

    return hes 
Example 5
Project: pysheds   Author: mdbartos   File: grid.py    License: GNU General Public License v3.0 6 votes vote down vote up
def facet_flow(self, e0, e1, e2, d1=1, d2=1):
        s1 = (e0 - e1)/d1
        s2 = (e1 - e2)/d2
        r = np.arctan2(s2, s1)
        s = np.hypot(s1, s2)
        diag_angle    = np.arctan2(d2, d1)
        diag_distance = np.hypot(d1, d2)
        b0 = (r < 0)
        b1 = (r > diag_angle)
        r[b0] = 0
        s[b0] = s1[b0]
        if isinstance(diag_angle, np.ndarray):
            r[b1] = diag_angle[b1]
        else:
            r[b1] = diag_angle
        s[b1] = ((e0 - e2)/diag_distance)[b1]
        return r, s 
Example 6
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
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,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 7
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
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 8
Project: facade-segmentation   Author: jfemiani   File: rectify.py    License: MIT License 6 votes vote down vote up
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 9
Project: facade-segmentation   Author: jfemiani   File: rectify.py    License: MIT License 6 votes vote down vote up
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 10
Project: python3_ios   Author: holzschu   File: data_browser.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def onpick(self, event):

        if event.artist != line:
            return True

        N = len(event.ind)
        if not N:
            return True

        # the click locations
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata

        distances = np.hypot(x - xs[event.ind], y - ys[event.ind])
        indmin = distances.argmin()
        dataind = event.ind[indmin]

        self.lastind = dataind
        self.update() 
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,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
Example 12
Project: pySINDy   Author: luckystarufo   File: test_ufunc.py    License: MIT License 6 votes vote down vote up
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 13
Project: FLORIS   Author: WISDEM   File: turbine.py    License: Apache License 2.0 6 votes vote down vote up
def _create_swept_area_grid(self):
        # TODO: add validity check:
        # rotor points has a minimum in order to always include points inside
        # the disk ... 2?
        #
        # the grid consists of the y,z coordinates of the discrete points which
        # lie within the rotor area: [(y1,z1), (y2,z2), ... , (yN, zN)]

        # update:
        # using all the grid point because that how roald did it.
        # are the points outside of the rotor disk used later?

        # determine the dimensions of the square grid
        num_points = int(np.round(np.sqrt(self.grid_point_count)))
        # syntax: np.linspace(min, max, n points)
        horizontal = np.linspace(-self.rotor_radius, self.rotor_radius, num_points)
        vertical = np.linspace(-self.rotor_radius, self.rotor_radius, num_points)

        # build the grid with all of the points
        grid = [(h, vertical[i]) for i in range(num_points) for h in horizontal]

        # keep only the points in the swept area
        grid = [point for point in grid if np.hypot(point[0], point[1]) < self.rotor_radius]

        return grid 
Example 14
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: symbol.py    License: Apache License 2.0 5 votes vote down vote up
def hypot(left, right):
    """Given the "legs" of a right triangle, returns its hypotenuse.

    Equivalent to :math:`\\sqrt(left^2 + right^2)`, element-wise.
    Both inputs can be Symbol or scalar number. Broadcasting is not supported.

    Parameters
    ---------
    left : Symbol or scalar
        First leg of the triangle(s).
    right : Symbol or scalar
        Second leg of the triangle(s).

    Returns
    -------
    Symbol or scalar
        The hypotenuse of the triangle(s)

    Examples
    --------
    >>> mx.sym.hypot(3, 4)
    5.0
    >>> x = mx.sym.Variable('x')
    >>> y = mx.sym.Variable('y')
    >>> z = mx.sym.hypot(x, 4)
    >>> z.eval(x=mx.nd.array([3,5,2]))[0].asnumpy()
    array([ 5.,  6.40312433,  4.47213602], dtype=float32)
    >>> z = mx.sym.hypot(x, y)
    >>> z.eval(x=mx.nd.array([3,4]), y=mx.nd.array([10,2]))[0].asnumpy()
    array([ 10.44030666,   4.47213602], dtype=float32)
    """
    if isinstance(left, Symbol) and isinstance(right, Symbol):
        return _internal._Hypot(left, right)
    if isinstance(left, Symbol) and isinstance(right, Number):
        return _internal._HypotScalar(left, scalar=right)
    if isinstance(left, Number) and isinstance(right, Symbol):
        return _internal._HypotScalar(right, scalar=left)
    if isinstance(left, Number) and isinstance(right, Number):
        return _numpy.hypot(left, right)
    else:
        raise TypeError('types (%s, %s) not supported' % (str(type(left)), str(type(right)))) 
Example 15
Project: pulse2percept   Author: pulse2percept   File: geometry.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def cart2pol(x, y):
    """Convert Cartesian to polar coordinates"""
    theta = np.arctan2(y, x)
    rho = np.hypot(x, y)
    return theta, rho 
Example 16
Project: mplcursors   Author: anntzer   File: _pick_info.py    License: MIT License 5 votes vote down vote up
def _(artist, event):
    # No need to call `line.contains` as we're going to redo the work anyways
    # (also see matplotlib/matplotlib#6645, though that's fixed in mpl2.1).

    # Always work in screen coordinates, as this is how we need to compute
    # distances.  Note that the artist transform may be different from the axes
    # transform (e.g., for axvline).
    xy = event.x, event.y
    data_xy = artist.get_xydata()
    data_screen_xy = artist.get_transform().transform(data_xy)
    sels = []
    # If markers are visible, find the closest vertex.
    if artist.get_marker() not in ["None", "none", " ", "", None]:
        ds = np.hypot(*(xy - data_screen_xy).T)
        try:
            argmin = np.nanargmin(ds)
        except ValueError:  # Raised by nanargmin([nan]).
            pass
        else:
            target = _with_attrs(
                _untransform(  # More precise than transforming back.
                    data_xy[argmin], data_screen_xy[argmin], artist.axes),
                index=argmin)
            sels.append(Selection(artist, target, ds[argmin], None, None))
    # If lines are visible, find the closest projection.
    if (artist.get_linestyle() not in ["None", "none", " ", "", None]
            and len(artist.get_xydata()) > 1):
        sel = _compute_projection_pick(artist, artist.get_path(), xy)
        if sel is not None:
            sel.target.index = {
                "_draw_lines": lambda _, index: index,
                "_draw_steps_pre": Index.pre_index,
                "_draw_steps_mid": Index.mid_index,
                "_draw_steps_post": Index.post_index}[
                    Line2D.drawStyles[artist.get_drawstyle()]](
                        len(data_xy), sel.target.index)
            sels.append(sel)
    sel = min(sels, key=lambda sel: sel.dist, default=None)
    return sel if sel and sel.dist < artist.get_pickradius() else None 
Example 17
Project: mplcursors   Author: anntzer   File: _pick_info.py    License: MIT License 5 votes vote down vote up
def _(artist, event):
    offsets = artist.get_offsets()
    paths = artist.get_paths()
    if _is_scatter(artist):
        # Use the C implementation to prune the list of segments -- but only
        # for scatter plots as that implementation is inconsistent with Line2D
        # for segment-like collections (matplotlib/matplotlib#17279).
        contains, info = artist.contains(event)
        if not contains:
            return
        inds = info["ind"]
        offsets = artist.get_offsets()[inds]
        offsets_screen = artist.get_offset_transform().transform(offsets)
        ds = np.hypot(*(offsets_screen - [event.x, event.y]).T)
        argmin = ds.argmin()
        target = _with_attrs(
            _untransform(offsets[argmin], offsets_screen[argmin], artist.axes),
            index=inds[argmin])
        return Selection(artist, target, ds[argmin], None, None)
    else:
        # Note that this won't select implicitly closed paths.
        sels = [*filter(None, [
            _compute_projection_pick(
                artist,
                Affine2D().translate(*offsets[ind % len(offsets)])
                .transform_path(paths[ind % len(paths)]),
                (event.x, event.y))
            for ind in range(max(len(offsets), len(paths)))])]
        if not sels:
            return None
        idx = min(range(len(sels)), key=lambda idx: sels[idx].dist)
        sel = sels[idx]
        if sel.dist >= artist.get_pickradius():
            return None
        sel = sel._replace(artist=artist)
        sel.target.index = (idx, sel.target.index)
        return sel 
Example 18
Project: mplcursors   Author: anntzer   File: _pick_info.py    License: MIT License 5 votes vote down vote up
def _(artist, event):
    offsets = artist.get_offsets()
    offsets_screen = artist.get_offset_transform().transform(offsets)
    ds = np.hypot(*(offsets_screen - [event.x, event.y]).T)
    argmin = np.nanargmin(ds)
    if ds[argmin] < artist.get_pickradius():
        target = _with_attrs(
            _untransform(offsets[argmin], offsets_screen[argmin], artist.axes),
            index=argmin)
        return Selection(artist, target, ds[argmin], None, None)
    else:
        return None 
Example 19
Project: terrain-erosion-3-ways   Author: dandrino   File: util.py    License: MIT License 5 votes vote down vote up
def fbm(shape, p, lower=-np.inf, upper=np.inf):
  freqs = tuple(np.fft.fftfreq(n, d=1.0 / n) for n in shape)
  freq_radial = np.hypot(*np.meshgrid(*freqs))
  envelope = (np.power(freq_radial, p, where=freq_radial!=0) *
              (freq_radial > lower) * (freq_radial < upper))
  envelope[0][0] = 0.0
  phase_noise = np.exp(2j * np.pi * np.random.rand(*shape))
  return normalize(np.real(np.fft.ifft2(np.fft.fft2(phase_noise) * envelope)))


# Returns each value of `a` with coordinates offset by `offset` (via complex 
# values). The values at the new coordiantes are the linear interpolation of
# neighboring values in `a`. 
Example 20
Project: terrain-erosion-3-ways   Author: dandrino   File: util.py    License: MIT License 5 votes vote down vote up
def gaussian_blur(a, sigma=1.0):
  freqs = tuple(np.fft.fftfreq(n, d=1.0 / n) for n in a.shape)
  freq_radial = np.hypot(*np.meshgrid(*freqs))
  sigma2 = sigma**2
  g = lambda x: ((2 * np.pi * sigma2) ** -0.5) * np.exp(-0.5 * (x / sigma)**2)
  kernel = g(freq_radial)
  kernel /= kernel.sum()
  return np.fft.ifft2(np.fft.fft2(a) * np.fft.fft2(kernel)).real 
Example 21
Project: terrain-erosion-3-ways   Author: dandrino   File: river_network.py    License: MIT License 5 votes vote down vote up
def bump(shape, sigma):
  [y, x] = np.meshgrid(*map(np.arange, shape))
  r = np.hypot(x - shape[0] / 2, y - shape[1] / 2)
  c = min(shape) / 2
  return np.tanh(np.maximum(c - r, 0.0) / sigma)


# Returns a list of heights for each point in `points`. 
Example 22
Project: Computable   Author: ktraunmueller   File: testfuncs.py    License: MIT License 5 votes vote down vote up
def cosine_peak(x, y):
    circle = np.hypot(80 * x - 40.0, 90 * y - 45.)
    f = np.exp(-0.04 * circle) * np.cos(0.15 * circle)
    return f 
Example 23
Project: Computable   Author: ktraunmueller   File: testfuncs.py    License: MIT License 5 votes vote down vote up
def plot_cc(tri, edgecolor=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if edgecolor is None:
        edgecolor = (0, 0, 1, 0.2)
    dxy = (np.array([(tri.x[i], tri.y[i]) for i, j, k in tri.triangle_nodes])
        - tri.circumcenters)
    r = np.hypot(dxy[:, 0], dxy[:, 1])
    ax = pl.gca()
    for i in xrange(len(r)):
        p = mpl.patches.Circle(tri.circumcenters[i], r[i],
                               resolution=100, edgecolor=edgecolor,
                               facecolor=(1, 1, 1, 0), linewidth=0.2)
        ax.add_patch(p)
    pl.draw_if_interactive() 
Example 24
Project: Computable   Author: ktraunmueller   File: quiver.py    License: MIT License 5 votes vote down vote up
def _dots_per_unit(self, units):
        """
        Return a scale factor for converting from units to pixels
        """
        ax = self.ax
        if units in ('x', 'y', 'xy'):
            if units == 'x':
                dx0 = ax.viewLim.width
                dx1 = ax.bbox.width
            elif units == 'y':
                dx0 = ax.viewLim.height
                dx1 = ax.bbox.height
            else:  # 'xy' is assumed
                dxx0 = ax.viewLim.width
                dxx1 = ax.bbox.width
                dyy0 = ax.viewLim.height
                dyy1 = ax.bbox.height
                dx1 = np.hypot(dxx1, dyy1)
                dx0 = np.hypot(dxx0, dyy0)
            dx = dx1 / dx0
        else:
            if units == 'width':
                dx = ax.bbox.width
            elif units == 'height':
                dx = ax.bbox.height
            elif units == 'dots':
                dx = 1.0
            elif units == 'inches':
                dx = ax.figure.dpi
            else:
                raise ValueError('unrecognized units')
        return dx 
Example 25
Project: Computable   Author: ktraunmueller   File: quiver.py    License: MIT License 5 votes vote down vote up
def set_UVC(self, U, V, C=None):
        self.u = ma.masked_invalid(U, copy=False).ravel()
        self.v = ma.masked_invalid(V, copy=False).ravel()
        if C is not None:
            c = ma.masked_invalid(C, copy=False).ravel()
            x, y, u, v, c = delete_masked_points(self.x.ravel(),
                                                 self.y.ravel(),
                                                 self.u, self.v, c)
        else:
            x, y, u, v = delete_masked_points(self.x.ravel(), self.y.ravel(),
                                              self.u, self.v)

        magnitude = np.hypot(u, v)
        flags, barbs, halves, empty = self._find_tails(magnitude,
                                                       self.rounding,
                                                       **self.barb_increments)

        # Get the vertices for each of the barbs

        plot_barbs = self._make_barbs(u, v, flags, barbs, halves, empty,
                                      self._length, self._pivot, self.sizes,
                                      self.fill_empty, self.flip)
        self.set_verts(plot_barbs)

        # Set the color array
        if C is not None:
            self.set_array(c)

        # Update the offsets in case the masked data changed
        xy = np.hstack((x[:, np.newaxis], y[:, np.newaxis]))
        self._offsets = xy 
Example 26
Project: Computable   Author: ktraunmueller   File: test_kdtree.py    License: MIT License 5 votes vote down vote up
def test_max_one_side(self):
        assert_almost_equal(self.rect.max_distance_point([0.5,1.5]),np.hypot(0.5,1.5)) 
Example 27
Project: sea_ice_drift   Author: nansencenter   File: ftlib.py    License: GNU General Public License v3.0 5 votes vote down vote up
def lstsq_filter(x1, y1, x2, y2, psi=200, order=2, **kwargs):
    ''' Remove vectors that don't fit the model x1 = f(x2, y2)^n

    Fit the model x1 = f(x2, y2)^n using least squares method
    Simulate x1 using the model
    Compare actual and simulated x1 and remove points where error is too high
    Parameters
    ----------
        x1, y1, x2, y2 : coordinates of start and end of displacement [pixels]
        psi : threshold error between actual and simulated x1 [pixels]
    Returns
    -------
        x1 : 1D vector - filtered source X coordinates on img1, pix
        y1 : 1D vector - filtered source Y coordinates on img1, pix
        x2 : 1D vector - filtered destination X coordinates on img2, pix
        y2 : 1D vector - filtered destination Y coordinates on img2, pix
    '''
    if len(x1) == 0:
        return map(np.array, [[],[],[],[]])
    # interpolate using N-order polynomial
    x2sim, y2sim = interpolation_poly(x1, y1, x2, y2, x1, y1, order=order)

    # find error between actual and simulated x1
    err = np.hypot(x2 - x2sim, y2 - y2sim)

    # find pixels with error below psi
    gpi = err < psi

    print('LSTSQ filter: %d -> %d' % (len(x1), len(gpi[gpi])))
    return x1[gpi], y1[gpi], x2[gpi], y2[gpi] 
Example 28
Project: ms_deisotope   Author: mobiusklein   File: plot.py    License: Apache License 2.0 5 votes vote down vote up
def _draw_peak_pair(pair, edge_color='red', peak_color='orange', alpha=0.8, fontsize=12, label=None, rotation=45,
                    ax=None, **kwargs):
    p1, p2 = pair
    ax.plot((p1.mz, p2.mz), (p1.intensity, p2.intensity),
            color=edge_color, alpha=alpha, **kwargs)
    kwargs.setdefault("clip_on", False)
    clip_on = kwargs['clip_on']
    draw_peaklist(pair, ax=ax, alpha=0.4, color=peak_color)
    if label:
        midx = (p1.mz + p2.mz) / 2
        # interpolate the midpoint's height
        midy = (p1.intensity * (p2.mz - midx) +
                p2.intensity * (midx - p1.mz)) / (p2.mz - p1.mz)

        # find the angle of the line connecting the two peaks
        xlo = min(p1.mz, p2.mz)
        xhi = max(p1.mz, p2.mz)
        adj = xhi - xlo
        ylo = min(p1.intensity, p2.intensity)
        yhi = max(p1.intensity, p2.intensity)
        opp = yhi - ylo
        hypot = np.hypot(adj, opp) # pylint: disable=assignment-from-no-return
        rotation = np.arccos(adj / hypot)  # pylint: disable=assignment-from-no-return

        if isinstance(label, (list, tuple)):
            label = '-'.join(map(str, label))
        else:
            label = str(label)
        ax.text(midx, midy, label, fontsize=fontsize,
                ha='center', va='bottom', rotation=rotation, clip_on=clip_on) 
Example 29
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: widgets.py    License: MIT License 5 votes vote down vote up
def _onmove(self, event):
        """Cursor move event handler"""
        # Move the active vertex (ToolHandle).
        if self._active_handle_idx >= 0:
            idx = self._active_handle_idx
            self._xs[idx], self._ys[idx] = event.xdata, event.ydata
            # Also update the end of the polygon line if the first vertex is
            # the active handle and the polygon is completed.
            if idx == 0 and self._polygon_completed:
                self._xs[-1], self._ys[-1] = event.xdata, event.ydata

        # Move all vertices.
        elif 'move_all' in self.state and self.eventpress:
            dx = event.xdata - self.eventpress.xdata
            dy = event.ydata - self.eventpress.ydata
            for k in range(len(self._xs)):
                self._xs[k] = self._xs_at_press[k] + dx
                self._ys[k] = self._ys_at_press[k] + dy

        # Do nothing if completed or waiting for a move.
        elif (self._polygon_completed
              or 'move_vertex' in self.state or 'move_all' in self.state):
            return

        # Position pending vertex.
        else:
            # Calculate distance to the start vertex.
            x0, y0 = self.line.get_transform().transform((self._xs[0],
                                                          self._ys[0]))
            v0_dist = np.hypot(x0 - event.x, y0 - event.y)
            # Lock on to the start vertex if near it and ready to complete.
            if len(self._xs) > 3 and v0_dist < self.vertex_select_radius:
                self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0]
            else:
                self._xs[-1], self._ys[-1] = event.xdata, event.ydata

        self._draw_polygon() 
Example 30
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: patches.py    License: MIT License 5 votes vote down vote up
def connect(self, posA, posB):
            x1, y1 = posA
            x2, y2 = posB

            cosA = math.cos(math.radians(self.angleA))
            sinA = math.sin(math.radians(self.angleA))
            cosB = math.cos(math.radians(self.angleB))
            sinB = math.sin(math.radians(self.angleB))

            cx, cy = get_intersection(x1, y1, cosA, sinA,
                                      x2, y2, cosB, sinB)

            vertices = [(x1, y1)]
            codes = [Path.MOVETO]

            if self.rad == 0.:
                vertices.append((cx, cy))
                codes.append(Path.LINETO)
            else:
                dx1, dy1 = x1 - cx, y1 - cy
                d1 = np.hypot(dx1, dy1)
                f1 = self.rad / d1
                dx2, dy2 = x2 - cx, y2 - cy
                d2 = np.hypot(dx2, dy2)
                f2 = self.rad / d2
                vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
                                 (cx, cy),
                                 (cx + dx2 * f2, cy + dy2 * f2)])
                codes.extend([Path.LINETO, Path.CURVE3, Path.CURVE3])

            vertices.append((x2, y2))
            codes.append(Path.LINETO)

            return Path(vertices, codes)