Python numpy.fix() Examples

The following are 30 code examples for showing how to use numpy.fix(). 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: feets   Author: quatrope   File: ext_dmdt.py    License: MIT License 6 votes vote down vote up
def fit(self, magnitude, time, dt_bins, dm_bins):
        def delta_calc(idx):
            t0 = time[idx]
            m0 = magnitude[idx]
            deltat = time[idx + 1 :] - t0
            deltam = magnitude[idx + 1 :] - m0

            deltat[np.where(deltat < 0)] *= -1
            deltam[np.where(deltat < 0)] *= -1

            return np.column_stack((deltat, deltam))

        lc_len = len(time)
        n_vals = int(0.5 * lc_len * (lc_len - 1))

        deltas = np.vstack(tuple(delta_calc(idx) for idx in range(lc_len - 1)))

        deltat = deltas[:, 0]
        deltam = deltas[:, 1]

        bins = [dt_bins, dm_bins]
        counts = np.histogram2d(deltat, deltam, bins=bins, normed=False)[0]
        result = np.fix(255.0 * counts / n_vals + 0.999).astype(int)

        return {"DMDT": result} 
Example 2
Project: recruit   Author: Frank-qlu   File: test_ufunclike.py    License: Apache License 2.0 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 3
Project: vnpy_crypto   Author: birforce   File: test_ufunclike.py    License: MIT License 6 votes vote down vote up
def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res

            def __array_wrap__(self, obj, context=None):
                obj.metadata = self.metadata
                return obj

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1, -1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')

        # check 0d arrays don't decay to scalars
        m0d = m[0,...]
        m0d.metadata = 'bar'
        f0d = ufl.fix(m0d)
        assert_(isinstance(f0d, MyArray))
        assert_equal(f0d.metadata, 'bar') 
Example 4
Project: vnpy_crypto   Author: birforce   File: test_ufunclike.py    License: MIT License 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 5
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunclike.py    License: MIT License 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 6
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_ufunclike.py    License: MIT License 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 7
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 8
Project: pySINDy   Author: luckystarufo   File: test_ufunclike.py    License: MIT License 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 9
Project: mxnet-lambda   Author: awslabs   File: test_ufunclike.py    License: Apache License 2.0 6 votes vote down vote up
def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res

            def __array_wrap__(self, obj, context=None):
                obj.metadata = self.metadata
                return obj

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1, -1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')

        # check 0d arrays don't decay to scalars
        m0d = m[0,...]
        m0d.metadata = 'bar'
        f0d = ufl.fix(m0d)
        assert_(isinstance(f0d, MyArray))
        assert_equal(f0d.metadata, 'bar') 
Example 10
Project: mxnet-lambda   Author: awslabs   File: test_ufunclike.py    License: Apache License 2.0 6 votes vote down vote up
def test_scalar(self):
        x = np.inf
        actual = np.isposinf(x)
        expected = np.True_
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        x = -3.4
        actual = np.fix(x)
        expected = np.float64(-3.0)
        assert_equal(actual, expected)
        assert_equal(type(actual), type(expected))

        out = np.array(0.0)
        actual = np.fix(x, out=out)
        assert_(actual is out) 
Example 11
Project: tensorrt_demos   Author: jkjung-avt   File: mtcnn.py    License: MIT License 6 votes vote down vote up
def convert_to_1x1(boxes):
    """Convert detection boxes to 1:1 sizes

    # Arguments
        boxes: numpy array, shape (n,5), dtype=float32

    # Returns
        boxes_1x1
    """
    boxes_1x1 = boxes.copy()
    hh = boxes[:, 3] - boxes[:, 1] + 1.
    ww = boxes[:, 2] - boxes[:, 0] + 1.
    mm = np.maximum(hh, ww)
    boxes_1x1[:, 0] = boxes[:, 0] + ww * 0.5 - mm * 0.5
    boxes_1x1[:, 1] = boxes[:, 1] + hh * 0.5 - mm * 0.5
    boxes_1x1[:, 2] = boxes_1x1[:, 0] + mm - 1.
    boxes_1x1[:, 3] = boxes_1x1[:, 1] + mm - 1.
    boxes_1x1[:, 0:4] = np.fix(boxes_1x1[:, 0:4])
    return boxes_1x1 
Example 12
Project: tensorrt_demos   Author: jkjung-avt   File: mtcnn.py    License: MIT License 6 votes vote down vote up
def detect(self, img, minsize=40):
        """detect()

        This function handles rescaling of the input image if it's
        larger than 1280x720.
        """
        if img is None:
            raise ValueError
        img_h, img_w, _ = img.shape
        scale = min(720. / img_h, 1280. / img_w)
        if scale < 1.0:
            new_h = int(np.ceil(img_h * scale))
            new_w = int(np.ceil(img_w * scale))
            img = cv2.resize(img, (new_w, new_h))
            minsize = max(int(np.ceil(minsize * scale)), 40)
        dets, landmarks = self._detect_1280x720(img, minsize)
        if scale < 1.0:
            dets[:, :-1] = np.fix(dets[:, :-1] / scale)
            landmarks = np.fix(landmarks / scale)
        return dets, landmarks 
Example 13
Project: AMFM_decompy   Author: bjbschmitt   File: pYAAPT.py    License: MIT License 6 votes vote down vote up
def fix(self):
        if self.PITCH_HALF > 0:
            nz_pitch = self.samp_values[self.samp_values > 0]
            idx = self.samp_values < (np.mean(nz_pitch)-self.PITCH_HALF_SENS *
                                      np.std(nz_pitch))
            if self.PITCH_HALF == 1:
                self.samp_values[idx] = 0
            elif self.PITCH_HALF == 2:
                self.samp_values[idx] = 2*self.samp_values[idx]

        if self.PITCH_DOUBLE > 0:
            nz_pitch = self.samp_values[self.samp_values > 0]
            idx = self.samp_values > (np.mean(nz_pitch)+self.PITCH_DOUBLE_SENS *
                                      np.std(nz_pitch))
            if self.PITCH_DOUBLE == 1:
                self.samp_values[idx] = 0
            elif self.PITCH_DOUBLE == 2:
                self.samp_values[idx] = 0.5*self.samp_values[idx] 
Example 14
Project: wradlib   Author: wradlib   File: util.py    License: MIT License 6 votes vote down vote up
def filter_window_cartesian(img, wsize, fun, scale, **kwargs):
    """Apply a filter of square window size `fsize` on a given \
    cartesian image `img`.

    Parameters
    ----------
    img : :class:`numpy:numpy.ndarray`
        2d array of values to which the filter is to be applied
    wsize : float
        Half size of the window centred on the pixel [m]
    fun : string
        name of the 2d filter from :mod:`scipy:scipy.ndimage`
    scale : tuple of 2 floats
        x and y scale of the cartesian grid [m]

    Returns
    -------
    output : :class:`numpy:numpy.ndarray`
        Array with the same shape as `img`, containing the filter's results.

    """
    fun = getattr(ndimage.filters, "%s_filter" % fun)
    size = np.fix(wsize / scale + 0.5).astype(int)
    data_filtered = fun(img, size, **kwargs)
    return data_filtered 
Example 15
Project: insightface   Author: deepinsight   File: detect_face.py    License: MIT License 5 votes vote down vote up
def generateBoundingBox(imap, reg, scale, t):
    # use heatmap to generate bounding boxes
    stride=2
    cellsize=12

    imap = np.transpose(imap)
    dx1 = np.transpose(reg[:,:,0])
    dy1 = np.transpose(reg[:,:,1])
    dx2 = np.transpose(reg[:,:,2])
    dy2 = np.transpose(reg[:,:,3])
    y, x = np.where(imap >= t)
    if y.shape[0]==1:
        dx1 = np.flipud(dx1)
        dy1 = np.flipud(dy1)
        dx2 = np.flipud(dx2)
        dy2 = np.flipud(dy2)
    score = imap[(y,x)]
    reg = np.transpose(np.vstack([ dx1[(y,x)], dy1[(y,x)], dx2[(y,x)], dy2[(y,x)] ]))
    if reg.size==0:
        reg = np.empty((0,3))
    bb = np.transpose(np.vstack([y,x]))
    q1 = np.fix((stride*bb+1)/scale)
    q2 = np.fix((stride*bb+cellsize-1+1)/scale)
    boundingbox = np.hstack([q1, q2, np.expand_dims(score,1), reg])
    return boundingbox, reg
 
# function pick = nms(boxes,threshold,type) 
Example 16
Project: recruit   Author: Frank-qlu   File: test_ufunclike.py    License: Apache License 2.0 5 votes vote down vote up
def test_fix(self):
        a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
        out = nx.zeros(a.shape, float)
        tgt = nx.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]])

        res = ufl.fix(a)
        assert_equal(res, tgt)
        res = ufl.fix(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
        assert_equal(ufl.fix(3.14), 3) 
Example 17
Project: recruit   Author: Frank-qlu   File: test_ufunclike.py    License: Apache License 2.0 5 votes vote down vote up
def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res

            def __array_wrap__(self, obj, context=None):
                if isinstance(obj, MyArray):
                    obj.metadata = self.metadata
                return obj

            def __array_finalize__(self, obj):
                self.metadata = getattr(obj, 'metadata', None)
                return self

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1, -1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')

        # check 0d arrays don't decay to scalars
        m0d = m[0,...]
        m0d.metadata = 'bar'
        f0d = ufl.fix(m0d)
        assert_(isinstance(f0d, MyArray))
        assert_equal(f0d.metadata, 'bar') 
Example 18
Project: recruit   Author: Frank-qlu   File: test_ufunclike.py    License: Apache License 2.0 5 votes vote down vote up
def test_deprecated(self):
        # NumPy 1.13.0, 2017-04-26
        assert_warns(DeprecationWarning, ufl.fix, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isposinf, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isneginf, [1, 2], y=nx.empty(2)) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_indexing.py    License: Apache License 2.0 5 votes vote down vote up
def test_getitem_setitem_ellipsis():
    s = Series(np.random.randn(10))

    np.fix(s)

    result = s[...]
    assert_series_equal(result, s)

    s[...] = 5
    assert (result == 5).all() 
Example 20
Project: mars   Author: mars-project   File: fix.py    License: Apache License 2.0 5 votes vote down vote up
def fix(x, out=None, **kwargs):
    """
    Round to nearest integer towards zero.

    Round a tensor of floats element-wise to nearest integer towards zero.
    The rounded values are returned as floats.

    Parameters
    ----------
    x   : array_like
        An tensor of floats to be rounded
    out : Tensor, optional
        Output tensor

    Returns
    -------
    out : Tensor of floats
        The array of rounded numbers

    See Also
    --------
    trunc, floor, ceil
    around : Round to given number of decimals

    Examples
    --------
    >>> import mars.tensor as mt

    >>> mt.fix(3.14).execute()
    3.0
    >>> mt.fix(3).execute()
    3.0
    >>> mt.fix([2.1, 2.9, -2.1, -2.9]).execute()
    array([ 2.,  2., -2., -2.])

    """
    op = TensorFix(**kwargs)
    return op(x, out=out) 
Example 21
Project: TNT   Author: GaoangW   File: detect_face.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generateBoundingBox(imap, reg, scale, t):
    """Use heatmap to generate bounding boxes"""
    stride=2
    cellsize=12

    imap = np.transpose(imap)
    dx1 = np.transpose(reg[:,:,0])
    dy1 = np.transpose(reg[:,:,1])
    dx2 = np.transpose(reg[:,:,2])
    dy2 = np.transpose(reg[:,:,3])
    y, x = np.where(imap >= t)
    if y.shape[0]==1:
        dx1 = np.flipud(dx1)
        dy1 = np.flipud(dy1)
        dx2 = np.flipud(dx2)
        dy2 = np.flipud(dy2)
    score = imap[(y,x)]
    reg = np.transpose(np.vstack([ dx1[(y,x)], dy1[(y,x)], dx2[(y,x)], dy2[(y,x)] ]))
    if reg.size==0:
        reg = np.empty((0,3))
    bb = np.transpose(np.vstack([y,x]))
    q1 = np.fix((stride*bb+1)/scale)
    q2 = np.fix((stride*bb+cellsize-1+1)/scale)
    boundingbox = np.hstack([q1, q2, np.expand_dims(score,1), reg])
    return boundingbox, reg
 
# function pick = nms(boxes,threshold,type) 
Example 22
Project: vnpy_crypto   Author: birforce   File: test_ufunclike.py    License: MIT License 5 votes vote down vote up
def test_fix(self):
        a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
        out = nx.zeros(a.shape, float)
        tgt = nx.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]])

        res = ufl.fix(a)
        assert_equal(res, tgt)
        res = ufl.fix(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
        assert_equal(ufl.fix(3.14), 3) 
Example 23
Project: vnpy_crypto   Author: birforce   File: test_ufunclike.py    License: MIT License 5 votes vote down vote up
def test_deprecated(self):
        # NumPy 1.13.0, 2017-04-26
        assert_warns(DeprecationWarning, ufl.fix, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isposinf, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isneginf, [1, 2], y=nx.empty(2)) 
Example 24
Project: vnpy_crypto   Author: birforce   File: test_indexing.py    License: MIT License 5 votes vote down vote up
def test_getitem_setitem_ellipsis():
    s = Series(np.random.randn(10))

    np.fix(s)

    result = s[...]
    assert_series_equal(result, s)

    s[...] = 5
    assert (result == 5).all() 
Example 25
Project: opensauce-python   Author: voicesauce   File: shrp.py    License: Apache License 2.0 5 votes vote down vote up
def two_max(x, lowerbound, upperbound, unit_len):
    """Return up to two successive maximum peaks and their indices in x.

    Return the magnitudes of the peaks and the indices as two lists.
    If the first maximum is less than zero, just return it.  Otherwise
    look to the right of the first maximum, and if there is a second
    maximum that is greater than zero, add that to the returned lists.

    lowerbound and upperbound comprise a closed interval, unlike the
    normal python half closed interval.  [RDM XXX: fix this?]

    """
    # XXX The above description is not completely accurate: there's a window to
    # the search for the second peak, but I don't understand the goal well
    # enough to describe it better, and the original comments are less precise.
    max_index = min(upperbound, len(x)-1)
    # "find the maximum value"
    mag = np.array([np.amax(x[lowerbound:upperbound+1])])
    index = np.where(x == mag)[0]
    if mag < 0:
        return mag, index
    harmonics = 2
    limit = 0.0625  # "1/8 octave"
    startpos = index[0] + int(round(np.log2(harmonics-limit)/unit_len))
    if startpos <= max_index:
        # "for example, 100hz-200hz is one octave, 200hz-250hz is 1/4octave"
        endpos = index[0] + int(round(np.log2(harmonics + limit)/unit_len))
        endpos = min(max_index, endpos)
        # "find the maximum value at right side of last maximum"
        mag2 = np.amax(x[startpos:endpos+1])
        index2 = np.where(x[startpos:] == mag2)[0][0] + startpos
        if mag2 > 0:
            mag = np.append(mag, mag2)
            index = np.append(index, index2)
    return mag, index


# ---- vda -----
# func_Get_SHRP does not use this, because CHECK_VOICING is always 0 
Example 26
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunclike.py    License: MIT License 5 votes vote down vote up
def test_fix(self):
        a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
        out = nx.zeros(a.shape, float)
        tgt = nx.array([[1., 1., 1., 1.], [-1., -1., -1., -1.]])

        res = ufl.fix(a)
        assert_equal(res, tgt)
        res = ufl.fix(a, out)
        assert_equal(res, tgt)
        assert_equal(out, tgt)
        assert_equal(ufl.fix(3.14), 3) 
Example 27
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunclike.py    License: MIT License 5 votes vote down vote up
def test_fix_with_subclass(self):
        class MyArray(nx.ndarray):
            def __new__(cls, data, metadata=None):
                res = nx.array(data, copy=True).view(cls)
                res.metadata = metadata
                return res

            def __array_wrap__(self, obj, context=None):
                if isinstance(obj, MyArray):
                    obj.metadata = self.metadata
                return obj

            def __array_finalize__(self, obj):
                self.metadata = getattr(obj, 'metadata', None)
                return self

        a = nx.array([1.1, -1.1])
        m = MyArray(a, metadata='foo')
        f = ufl.fix(m)
        assert_array_equal(f, nx.array([1, -1]))
        assert_(isinstance(f, MyArray))
        assert_equal(f.metadata, 'foo')

        # check 0d arrays don't decay to scalars
        m0d = m[0,...]
        m0d.metadata = 'bar'
        f0d = ufl.fix(m0d)
        assert_(isinstance(f0d, MyArray))
        assert_equal(f0d.metadata, 'bar') 
Example 28
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_ufunclike.py    License: MIT License 5 votes vote down vote up
def test_deprecated(self):
        # NumPy 1.13.0, 2017-04-26
        assert_warns(DeprecationWarning, ufl.fix, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isposinf, [1, 2], y=nx.empty(2))
        assert_warns(DeprecationWarning, ufl.isneginf, [1, 2], y=nx.empty(2)) 
Example 29
Project: qiskit-aer   Author: Qiskit   File: operators.py    License: Apache License 2.0 5 votes vote down vote up
def jmat(j, *args):
    """Higher-order spin operators:

    Args:
        j (float): Spin of operator

        args (str): Which operator to return 'x','y','z','+','-'.
                    If no args given, then output is ['x','y','z']

    Returns:
        Qobj: Requested spin operator(s).

    Raises:
        TypeError: Invalid input.
    """
    if (np.fix(2 * j) != 2 * j) or (j < 0):
        raise TypeError('j must be a non-negative integer or half-integer')

    if not args:
        return jmat(j, 'x'), jmat(j, 'y'), jmat(j, 'z')

    if args[0] == '+':
        A = _jplus(j)
    elif args[0] == '-':
        A = _jplus(j).getH()
    elif args[0] == 'x':
        A = 0.5 * (_jplus(j) + _jplus(j).getH())
    elif args[0] == 'y':
        A = -0.5 * 1j * (_jplus(j) - _jplus(j).getH())
    elif args[0] == 'z':
        A = _jz(j)
    else:
        raise TypeError('Invalid type')

    return Qobj(A) 
Example 30
Project: trax   Author: google   File: math_ops.py    License: Apache License 2.0 5 votes vote down vote up
def fix(x):
  def f(x):
    return tf.where(x < 0, tf.math.ceil(x), tf.math.floor(x))
  return _scalar(f, x, True)