Python numpy.modf() Examples

The following are 30 code examples of numpy.modf(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: test_eager_mode.py    From mars with Apache License 2.0 6 votes vote down vote up
def testMultipleOutputExecute(self):
        with option_context({'eager_mode': True}):
            data = np.random.random((5, 9))

            arr1 = mt.tensor(data.copy(), chunk_size=3)
            result = mt.modf(arr1)
            expected = np.modf(data)

            np.testing.assert_array_equal(result[0].fetch(), expected[0])
            np.testing.assert_array_equal(result[1].fetch(), expected[1])

            arr3 = mt.tensor(data.copy(), chunk_size=3)
            result1, result2, result3 = mt.split(arr3, 3, axis=1)
            expected = np.split(data, 3, axis=1)

            np.testing.assert_array_equal(result1.fetch(), expected[0])
            np.testing.assert_array_equal(result2.fetch(), expected[1])
            np.testing.assert_array_equal(result3.fetch(), expected[2]) 
Example #2
Source File: postprocess_utils.py    From coded with MIT License 6 votes vote down vote up
def convert_date(config, array):

    """ Convert date from years since 1970 to year """

    date_band = config['general']['date_band'] - 1
    if len(array.shape) == 3:
        array[date_band,:,:][array[date_band,:,:] > 0] += 1970
        doys = np.modf(array[date_band,:,:])[0]
        doys = ((doys * 365).astype(int)).astype(np.str)
        array[date_band,:,:] = np.core.defchararray.add(
	    		       array[date_band,:,:].astype(np.int).
			       astype(np.str), doys)
    else:
        array[array > 0] += 1970
        doys = np.modf(array)[0]
        doys = ((doys * 365).astype(int)).astype(np.str)
        array = np.core.defchararray.add(
	        array.astype(np.int).
	        astype(np.str), doys)
    return array 
Example #3
Source File: tile.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _round_frac(x, precision):
    """
    Round the fractional part of the given number
    """
    if not np.isfinite(x) or x == 0:
        return x
    else:
        frac, whole = np.modf(x)
        if whole == 0:
            digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
        else:
            digits = precision
        return np.around(x, digits) 
Example #4
Source File: thinkdsp.py    From Lie_to_me with MIT License 5 votes vote down vote up
def evaluate(self, ts):
        """Evaluates the signal at the given times.

        ts: float array of times
        
        returns: float wave array
        """
        ts = np.asarray(ts)
        cycles = self.freq * ts + self.offset / PI2
        frac, _ = np.modf(cycles)
        ys = (frac - 0.5)**2
        ys = normalize(unbias(ys), self.amp)
        return ys 
Example #5
Source File: thinkdsp.py    From Lie_to_me with MIT License 5 votes vote down vote up
def evaluate(self, ts):
        """Evaluates the signal at the given times.

        ts: float array of times
        
        returns: float wave array
        """
        ts = np.asarray(ts)
        cycles = self.freq * ts + self.offset / PI2
        frac, _ = np.modf(cycles)
        ys = frac**2 * (1-frac)
        ys = normalize(unbias(ys), self.amp)
        return ys 
Example #6
Source File: thinkdsp.py    From Lie_to_me with MIT License 5 votes vote down vote up
def evaluate(self, ts):
        """Evaluates the signal at the given times.

        ts: float array of times
        
        returns: float wave array
        """
        ts = np.asarray(ts)
        cycles = self.freq * ts + self.offset / PI2
        frac, _ = np.modf(cycles)
        ys = np.abs(frac - 0.5)
        ys = normalize(unbias(ys), self.amp)
        return ys 
Example #7
Source File: test_core.py    From openscm with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_timeseries_class(model, start_time, series):
    inseries = series[0]

    parameterset = model.parameters
    parameter = parameterset.timeseries(
        "Parameter",
        "",
        create_time_points(
            start_time, 24 * 3600, len(inseries), ParameterType.AVERAGE_TIMESERIES
        ),
        timeseries_type="average",
    )
    parameter.values = inseries

    assert parameter.values.shape == inseries.shape
    assert parameter.values.nbytes == inseries.nbytes
    assert parameter.values.dtype == inseries.dtype
    assert parameter.values.ndim == 1
    assert np.all(parameter.values[:] == parameter.values[:])
    assert str(parameter.values) == "timeseries({})".format(repr(inseries))

    np.testing.assert_allclose(np.add(parameter.values, inseries), 2 * inseries)
    assert np.sum(parameter.values) == np.sum(inseries)

    out = np.empty_like(inseries, dtype=float)
    np.sin(parameter.values, out=out)
    np.testing.assert_allclose(out, np.sin(inseries))

    out0 = np.empty_like(inseries, dtype=float)
    out1 = np.empty_like(inseries, dtype=float)
    np.modf(parameter.values, out=(out0, out1))
    out = np.modf(inseries)
    np.testing.assert_equal(out[0], out0)
    np.testing.assert_equal(out[1], out1) 
Example #8
Source File: marker_render.py    From robotics-rl-srl with MIT License 5 votes vote down vote up
def transformMarkerImage(self, marker_pixel_pos, marker_yaw, maker_scale):
        """

        :param marker_pixel_pos:
        :param marker_yaw:
        :param maker_scale:
        :return:
        """
        self.marker_yaw = marker_yaw
        self.marker_pixel_pos = np.float32(marker_pixel_pos).reshape((2, ))
        self.maker_scale = maker_scale
        self.M_marker_with_margin = cv2.getRotationMatrix2D((self.marker_image_with_margin.shape[1] / 2,
                                                             self.marker_image_with_margin.shape[0] / 2),
                                                            self.marker_yaw * 180 / np.pi, self.maker_scale)
        self.marker_pixel_pos_fraction, self.marker_pixel_pos_interger = np.modf(self.marker_pixel_pos)

        self.marker_pixel_pos_interger = self.marker_pixel_pos_interger.astype(np.int)
        self.M_marker_with_margin[0, 2] += \
            self.marker_pixel_pos_fraction[1] + self.roi_half_length - self.marker_image_with_margin.shape[0] / 2
        self.M_marker_with_margin[1, 2] += \
            self.marker_pixel_pos_fraction[0] + self.roi_half_length - self.marker_image_with_margin.shape[1] / 2

        self.marker_image_transformed = cv2.warpAffine(self.marker_image_with_margin, self.M_marker_with_margin,
                                                       (self.roi_length, self.roi_length))
        
        self.marker_weight_transformed = cv2.warpAffine(self.marker_weight, self.M_marker_with_margin,
                                                        (self.roi_length, self.roi_length))  # white: Marker part

        self.bg_weight = 1.0 - self.marker_weight_transformed  # white: origin image part 
Example #9
Source File: test_umath.py    From ImageFusion with MIT License 5 votes vote down vote up
def test_ufunc_override_out(self):
        class A(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs


        class B(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        a = A()
        b = B()
        res0 = np.multiply(a, b, 'out_arg')
        res1 = np.multiply(a, b, out='out_arg')
        res2 = np.multiply(2, b, 'out_arg')
        res3 = np.multiply(3, b, out='out_arg')
        res4 = np.multiply(a, 4, 'out_arg')
        res5 = np.multiply(a, 5, out='out_arg')

        assert_equal(res0['out'], 'out_arg')
        assert_equal(res1['out'], 'out_arg')
        assert_equal(res2['out'], 'out_arg')
        assert_equal(res3['out'], 'out_arg')
        assert_equal(res4['out'], 'out_arg')
        assert_equal(res5['out'], 'out_arg')

        # ufuncs with multiple output modf and frexp.
        res6 = np.modf(a, 'out0', 'out1')
        res7 = np.frexp(a, 'out0', 'out1')
        assert_equal(res6['out'][0], 'out0')
        assert_equal(res6['out'][1], 'out1')
        assert_equal(res7['out'][0], 'out0')
        assert_equal(res7['out'][1], 'out1') 
Example #10
Source File: tile.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _round_frac(x, precision):
    """
    Round the fractional part of the given number
    """
    if not np.isfinite(x) or x == 0:
        return x
    else:
        frac, whole = np.modf(x)
        if whole == 0:
            digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
        else:
            digits = precision
        return np.around(x, digits) 
Example #11
Source File: tile.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _round_frac(x, precision):
    """
    Round the fractional part of the given number
    """
    if not np.isfinite(x) or x == 0:
        return x
    else:
        frac, whole = np.modf(x)
        if whole == 0:
            digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
        else:
            digits = precision
        return np.around(x, digits) 
Example #12
Source File: block.py    From bifrost with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(self, input_rings, output_rings):
        """Generate a histogram from the input ring data
        @param[in] input_rings List with first ring containing
            data of interest. Must terminate before histogram
            is generated.
        @param[out] output_rings First ring in this list
            will contain the output histogram"""
        histogram = np.reshape(
            np.zeros(self.bins).astype(np.float32),
            (1, self.bins))
        tstart = None
        for span in self.iterate_ring_read(input_rings[0]):
            nchans = self.data_settings['frame_shape'][0]
            if tstart is None:
                tstart = self.data_settings['tstart']
            frequency = self.data_settings['fch1']
            for chan in range(nchans):
                modified_tstart = tstart - self.calculate_delay(
                    frequency,
                    self.data_settings['fch1'])
                frequency -= self.data_settings['foff']
                sort_indices = np.argsort(
                    self.calculate_bin_indices(
                        modified_tstart, self.data_settings['tsamp'],
                        span.data.shape[1] / nchans))
                sorted_data = span.data[0][chan::nchans][sort_indices]
                extra_elements = np.round(self.bins * (1 - np.modf(
                    float(span.data.shape[1] / nchans) / self.bins)[0])).astype(int)
                sorted_data = insert_zeros_evenly(sorted_data, extra_elements)
                histogram += np.sum(
                    sorted_data.reshape(self.bins, -1), 1).astype(np.float32)
            tstart += (self.data_settings['tsamp'] *
                       self.gulp_size * 8 / self.data_settings['nbit'] / nchans)
        self.out_gulp_size = self.bins * 4
        out_span_generator = self.iterate_ring_write(output_rings[0])
        out_span = out_span_generator.next()
        bifrost.memory.memcpy(
            out_span.data_view(dtype=np.float32),
            histogram) 
Example #13
Source File: utils.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def subpixel_indices(position, subsampling):
    """
    Convert decimal points to indices, given a subsampling factor.

    This discards the integer part of the position and uses only the decimal
    place, and converts this to a subpixel position depending on the
    subsampling specified. The center of a pixel corresponds to an integer
    position.

    Parameters
    ----------
    position : `~numpy.ndarray` or array_like
        Positions in pixels.
    subsampling : int
        Subsampling factor per pixel.

    Returns
    -------
    indices : `~numpy.ndarray`
        The integer subpixel indices corresponding to the input positions.

    Examples
    --------

    If no subsampling is used, then the subpixel indices returned are always 0:

    >>> from astropy.nddata.utils import subpixel_indices
    >>> subpixel_indices([1.2, 3.4, 5.6], 1)  # doctest: +FLOAT_CMP
    array([0., 0., 0.])

    If instead we use a subsampling of 2, we see that for the two first values
    (1.1 and 3.4) the subpixel position is 1, while for 5.6 it is 0. This is
    because the values of 1, 3, and 6 lie in the center of pixels, and 1.1 and
    3.4 lie in the left part of the pixels and 5.6 lies in the right part.

    >>> subpixel_indices([1.2, 3.4, 5.5], 2)  # doctest: +FLOAT_CMP
    array([1., 1., 0.])
    """
    # Get decimal points
    fractions = np.modf(np.asanyarray(position) + 0.5)[0]
    return np.floor(fractions * subsampling) 
Example #14
Source File: angle_utilities.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def degrees_to_dms(d):
    """
    Convert a floating-point degree value into a ``(degree, arcminute,
    arcsecond)`` tuple.
    """
    sign = np.copysign(1.0, d)

    (df, d) = np.modf(np.abs(d))  # (degree fraction, degree)
    (mf, m) = np.modf(df * 60.)  # (minute fraction, minute)
    s = mf * 60.

    return np.floor(sign * d), sign * np.floor(m), sign * s 
Example #15
Source File: angle_utilities.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hours_to_hms(h):
    """
    Convert an floating-point hour value into an ``(hour, minute,
    second)`` tuple.
    """

    sign = np.copysign(1.0, h)

    (hf, h) = np.modf(np.abs(h))  # (degree fraction, degree)
    (mf, m) = np.modf(hf * 60.0)  # (minute fraction, minute)
    s = mf * 60.0

    return (np.floor(sign * h), sign * np.floor(m), sign * s) 
Example #16
Source File: test_quantity_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modf_scalar(self):
        q = np.modf(9. * u.m / (600. * u.cm))
        assert q == (0.5 * u.dimensionless_unscaled,
                     1. * u.dimensionless_unscaled) 
Example #17
Source File: test_quantity_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modf_array(self):
        v = np.arange(10.) * u.m / (500. * u.cm)
        q = np.modf(v)
        n = np.modf(v.to_value(u.dimensionless_unscaled))
        assert q[0].unit == u.dimensionless_unscaled
        assert q[1].unit == u.dimensionless_unscaled
        assert all(q[0].value == n[0])
        assert all(q[1].value == n[1]) 
Example #18
Source File: test_umath.py    From keras-lambda with MIT License 5 votes vote down vote up
def test_ufunc_override_out(self):
        # 2016-01-29: NUMPY_UFUNC_DISABLED
        return

        class A(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        class B(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        a = A()
        b = B()
        res0 = np.multiply(a, b, 'out_arg')
        res1 = np.multiply(a, b, out='out_arg')
        res2 = np.multiply(2, b, 'out_arg')
        res3 = np.multiply(3, b, out='out_arg')
        res4 = np.multiply(a, 4, 'out_arg')
        res5 = np.multiply(a, 5, out='out_arg')

        assert_equal(res0['out'], 'out_arg')
        assert_equal(res1['out'], 'out_arg')
        assert_equal(res2['out'], 'out_arg')
        assert_equal(res3['out'], 'out_arg')
        assert_equal(res4['out'], 'out_arg')
        assert_equal(res5['out'], 'out_arg')

        # ufuncs with multiple output modf and frexp.
        res6 = np.modf(a, 'out0', 'out1')
        res7 = np.frexp(a, 'out0', 'out1')
        assert_equal(res6['out'][0], 'out0')
        assert_equal(res6['out'][1], 'out1')
        assert_equal(res7['out'][0], 'out0')
        assert_equal(res7['out'][1], 'out1') 
Example #19
Source File: thinkdsp.py    From Lie_to_me with MIT License 5 votes vote down vote up
def evaluate(self, ts):
        """Evaluates the signal at the given times.

        ts: float array of times
        
        returns: float wave array
        """
        ts = np.asarray(ts)
        cycles = self.freq * ts + self.offset / PI2
        frac, _ = np.modf(cycles)
        ys = self.amp * np.sign(unbias(frac))
        return ys 
Example #20
Source File: tile.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _round_frac(x, precision):
    """
    Round the fractional part of the given number
    """
    if not np.isfinite(x) or x == 0:
        return x
    else:
        frac, whole = np.modf(x)
        if whole == 0:
            digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
        else:
            digits = precision
        return np.around(x, digits) 
Example #21
Source File: modf.py    From mars with Apache License 2.0 5 votes vote down vote up
def execute(cls, ctx, op):
        inputs, device_id, xp = as_same_device(
            [ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)

        with device(device_id):
            kw = {'casting': op.casting}

            inputs_iter = iter(inputs)
            input = next(inputs_iter)
            if op.out1 is not None:
                out1 = next(inputs_iter)
            else:
                out1 = None
            if op.out2 is not None:
                out2 = next(inputs_iter)
            else:
                out2 = None
            if op.where is not None:
                where = kw['where'] = next(inputs_iter)
            else:
                where = None
            kw['order'] = op.order

            try:
                args = [input]
                if out1 is not None:
                    args.append(out1.copy())
                if out2 is not None:
                    args.append(out2.copy())
                y1, y2 = xp.modf(*args, **kw)
            except TypeError:
                if where is None:
                    raise
                y1, y2 = xp.modf(input)
                y1, y2 = xp.where(where, y1, out1), xp.where(where, y2, out2)

            for c, res in zip(op.outputs, (y1, y2)):
                ctx[c.key] = res 
Example #22
Source File: test_arithmetic_execution.py    From mars with Apache License 2.0 5 votes vote down vote up
def testModfExecution(self):
        data1 = np.random.random((5, 9))

        arr1 = tensor(data1.copy(), chunk_size=3)

        o1, o2 = modf(arr1)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.modf(data1))
        self.assertTrue(np.allclose(res, expected))

        o1, o2 = modf([0, 3.5])
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.modf([0, 3.5]))
        self.assertTrue(np.allclose(res, expected))

        arr1 = tensor(data1.copy(), chunk_size=3)
        o1 = zeros(data1.shape, chunk_size=3)
        o2 = zeros(data1.shape, chunk_size=3)
        modf(arr1, o1, o2)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.modf(data1))
        self.assertTrue(np.allclose(res, expected))

        data1 = sps.random(5, 9, density=.1)

        arr1 = tensor(data1.copy(), chunk_size=3)

        o1, o2 = modf(arr1)
        o = o1 + o2

        res = self.executor.execute_tensor(o, concat=True)[0]
        expected = sum(np.modf(data1.toarray()))
        np.testing.assert_equal(res.toarray(), expected) 
Example #23
Source File: test_arithmetic_execution.py    From mars with Apache License 2.0 5 votes vote down vote up
def testModfOrderExecution(self):
        data1 = np.random.random((5, 9))
        t = tensor(data1, chunk_size=3)

        o1, o2 = modf(t, order='F')
        res1, res2 = self.executor.execute_tileables([o1, o2])
        expected1, expected2 = np.modf(data1, order='F')
        np.testing.assert_allclose(res1, expected1)
        self.assertTrue(res1.flags['F_CONTIGUOUS'])
        self.assertFalse(res1.flags['C_CONTIGUOUS'])
        np.testing.assert_allclose(res2, expected2)
        self.assertTrue(res2.flags['F_CONTIGUOUS'])
        self.assertFalse(res2.flags['C_CONTIGUOUS']) 
Example #24
Source File: test_utils_test.py    From model-optimization with Apache License 2.0 5 votes vote down vote up
def common_asserts_for_test_data(self, data):
    """See base class."""
    frac_x, _ = np.modf(data.x)
    frac_encoded_x, _ = np.modf(data.encoded_x[self._ENCODED_VALUES_KEY])
    # The decimal places should be the same.
    self.assertAllClose(
        frac_x,
        frac_encoded_x,
        rtol=test_utils.DEFAULT_RTOL,
        atol=test_utils.DEFAULT_ATOL) 
Example #25
Source File: test_umath.py    From auto-alt-text-lambda-api with MIT License 5 votes vote down vote up
def test_ufunc_override_out(self):
        # 2016-01-29: NUMPY_UFUNC_DISABLED
        return

        class A(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        class B(object):
            def __numpy_ufunc__(self, ufunc, method, pos, inputs, **kwargs):
                return kwargs

        a = A()
        b = B()
        res0 = np.multiply(a, b, 'out_arg')
        res1 = np.multiply(a, b, out='out_arg')
        res2 = np.multiply(2, b, 'out_arg')
        res3 = np.multiply(3, b, out='out_arg')
        res4 = np.multiply(a, 4, 'out_arg')
        res5 = np.multiply(a, 5, out='out_arg')

        assert_equal(res0['out'], 'out_arg')
        assert_equal(res1['out'], 'out_arg')
        assert_equal(res2['out'], 'out_arg')
        assert_equal(res3['out'], 'out_arg')
        assert_equal(res4['out'], 'out_arg')
        assert_equal(res5['out'], 'out_arg')

        # ufuncs with multiple output modf and frexp.
        res6 = np.modf(a, 'out0', 'out1')
        res7 = np.frexp(a, 'out0', 'out1')
        assert_equal(res6['out'][0], 'out0')
        assert_equal(res6['out'][1], 'out1')
        assert_equal(res7['out'][0], 'out0')
        assert_equal(res7['out'][1], 'out1') 
Example #26
Source File: tile.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _round_frac(x, precision):
    """
    Round the fractional part of the given number
    """
    if not np.isfinite(x) or x == 0:
        return x
    else:
        frac, whole = np.modf(x)
        if whole == 0:
            digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision
        else:
            digits = precision
        return np.around(x, digits) 
Example #27
Source File: thinkdsp.py    From Lie_to_me with MIT License 5 votes vote down vote up
def evaluate(self, ts):
        """Evaluates the signal at the given times.

        ts: float array of times
        
        returns: float wave array
        """
        ts = np.asarray(ts)
        cycles = self.freq * ts + self.offset / PI2
        frac, _ = np.modf(cycles)
        ys = normalize(unbias(frac), self.amp)
        return ys 
Example #28
Source File: tile.py    From Computable with MIT License 5 votes vote down vote up
def _format_label(x, precision=3):
    fmt_str = '%%.%dg' % precision
    if np.isinf(x):
        return str(x)
    elif com.is_float(x):
        frac, whole = np.modf(x)
        sgn = '-' if x < 0 else ''
        whole = abs(whole)
        if frac != 0.0:
            val = fmt_str % frac

            # rounded up or down
            if '.' not in val:
                if x < 0:
                    return '%d' % (-whole - 1)
                else:
                    return '%d' % (whole + 1)

            if 'e' in val:
                return _trim_zeros(fmt_str % x)
            else:
                val = _trim_zeros(val)
                if '.' in val:
                    return sgn + '.'.join(('%d' % whole, val.split('.')[1]))
                else:  # pragma: no cover
                    return sgn + '.'.join(('%d' % whole, val))
        else:
            return sgn + '%0.f' % whole
    else:
        return str(x) 
Example #29
Source File: test_umath.py    From coffeegrindsize with MIT License 4 votes vote down vote up
def test_ufunc_override_out(self):

        class A(object):
            def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
                return kwargs

        class B(object):
            def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
                return kwargs

        a = A()
        b = B()
        res0 = np.multiply(a, b, 'out_arg')
        res1 = np.multiply(a, b, out='out_arg')
        res2 = np.multiply(2, b, 'out_arg')
        res3 = np.multiply(3, b, out='out_arg')
        res4 = np.multiply(a, 4, 'out_arg')
        res5 = np.multiply(a, 5, out='out_arg')

        assert_equal(res0['out'][0], 'out_arg')
        assert_equal(res1['out'][0], 'out_arg')
        assert_equal(res2['out'][0], 'out_arg')
        assert_equal(res3['out'][0], 'out_arg')
        assert_equal(res4['out'][0], 'out_arg')
        assert_equal(res5['out'][0], 'out_arg')

        # ufuncs with multiple output modf and frexp.
        res6 = np.modf(a, 'out0', 'out1')
        res7 = np.frexp(a, 'out0', 'out1')
        assert_equal(res6['out'][0], 'out0')
        assert_equal(res6['out'][1], 'out1')
        assert_equal(res7['out'][0], 'out0')
        assert_equal(res7['out'][1], 'out1')

        # While we're at it, check that default output is never passed on.
        assert_(np.sin(a, None) == {})
        assert_(np.sin(a, out=None) == {})
        assert_(np.sin(a, out=(None,)) == {})
        assert_(np.modf(a, None) == {})
        assert_(np.modf(a, None, None) == {})
        assert_(np.modf(a, out=(None, None)) == {})
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', '', DeprecationWarning)
            assert_(np.modf(a, out=None) == {})
            assert_(w[0].category is DeprecationWarning)

        # don't give positional and output argument, or too many arguments.
        # wrong number of arguments in the tuple is an error too.
        assert_raises(TypeError, np.multiply, a, b, 'one', out='two')
        assert_raises(TypeError, np.multiply, a, b, 'one', 'two')
        assert_raises(ValueError, np.multiply, a, b, out=('one', 'two'))
        assert_raises(ValueError, np.multiply, a, out=())
        assert_raises(TypeError, np.modf, a, 'one', out=('two', 'three'))
        assert_raises(TypeError, np.modf, a, 'one', 'two', 'three')
        assert_raises(ValueError, np.modf, a, out=('one', 'two', 'three'))
        assert_raises(ValueError, np.modf, a, out=('one',)) 
Example #30
Source File: test_half.py    From keras-lambda with MIT License 4 votes vote down vote up
def test_half_ufuncs(self):
        """Test the various ufuncs"""

        a = np.array([0, 1, 2, 4, 2], dtype=float16)
        b = np.array([-2, 5, 1, 4, 3], dtype=float16)
        c = np.array([0, -1, -np.inf, np.nan, 6], dtype=float16)

        assert_equal(np.add(a, b), [-2, 6, 3, 8, 5])
        assert_equal(np.subtract(a, b), [2, -4, 1, 0, -1])
        assert_equal(np.multiply(a, b), [0, 5, 2, 16, 6])
        assert_equal(np.divide(a, b), [0, 0.199951171875, 2, 1, 0.66650390625])

        assert_equal(np.equal(a, b), [False, False, False, True, False])
        assert_equal(np.not_equal(a, b), [True, True, True, False, True])
        assert_equal(np.less(a, b), [False, True, False, False, True])
        assert_equal(np.less_equal(a, b), [False, True, False, True, True])
        assert_equal(np.greater(a, b), [True, False, True, False, False])
        assert_equal(np.greater_equal(a, b), [True, False, True, True, False])
        assert_equal(np.logical_and(a, b), [False, True, True, True, True])
        assert_equal(np.logical_or(a, b), [True, True, True, True, True])
        assert_equal(np.logical_xor(a, b), [True, False, False, False, False])
        assert_equal(np.logical_not(a), [True, False, False, False, False])

        assert_equal(np.isnan(c), [False, False, False, True, False])
        assert_equal(np.isinf(c), [False, False, True, False, False])
        assert_equal(np.isfinite(c), [True, True, False, False, True])
        assert_equal(np.signbit(b), [True, False, False, False, False])

        assert_equal(np.copysign(b, a), [2, 5, 1, 4, 3])

        assert_equal(np.maximum(a, b), [0, 5, 2, 4, 3])
        x = np.maximum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [0, 5, 1, 0, 6])
        assert_equal(np.minimum(a, b), [-2, 1, 1, 4, 2])
        x = np.minimum(b, c)
        assert_(np.isnan(x[3]))
        x[3] = 0
        assert_equal(x, [-2, -1, -np.inf, 0, 3])
        assert_equal(np.fmax(a, b), [0, 5, 2, 4, 3])
        assert_equal(np.fmax(b, c), [0, 5, 1, 4, 6])
        assert_equal(np.fmin(a, b), [-2, 1, 1, 4, 2])
        assert_equal(np.fmin(b, c), [-2, -1, -np.inf, 4, 3])

        assert_equal(np.floor_divide(a, b), [0, 0, 2, 1, 0])
        assert_equal(np.remainder(a, b), [0, 1, 0, 0, 2])
        assert_equal(np.square(b), [4, 25, 1, 16, 9])
        assert_equal(np.reciprocal(b), [-0.5, 0.199951171875, 1, 0.25, 0.333251953125])
        assert_equal(np.ones_like(b), [1, 1, 1, 1, 1])
        assert_equal(np.conjugate(b), b)
        assert_equal(np.absolute(b), [2, 5, 1, 4, 3])
        assert_equal(np.negative(b), [2, -5, -1, -4, -3])
        assert_equal(np.sign(b), [-1, 1, 1, 1, 1])
        assert_equal(np.modf(b), ([0, 0, 0, 0, 0], b))
        assert_equal(np.frexp(b), ([-0.5, 0.625, 0.5, 0.5, 0.75], [2, 3, 1, 3, 2]))
        assert_equal(np.ldexp(b, [0, 1, 2, 4, 2]), [-2, 10, 4, 64, 12])