Python numpy.modf() Examples

The following are 30 code examples for showing how to use numpy.modf(). 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: mars   Author: mars-project   File: test_eager_mode.py    License: 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
Project: coded   Author: bullocke   File: postprocess_utils.py    License: 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
Project: recruit   Author: Frank-qlu   File: tile.py    License: 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 4
Project: mars   Author: mars-project   File: modf.py    License: 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 5
Project: mars   Author: mars-project   File: test_arithmetic_execution.py    License: 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 6
Project: mars   Author: mars-project   File: test_arithmetic_execution.py    License: 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 7
Project: model-optimization   Author: tensorflow   File: test_utils_test.py    License: 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 8
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: 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 9
Project: vnpy_crypto   Author: birforce   File: tile.py    License: 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 10
Project: Computable   Author: ktraunmueller   File: tile.py    License: 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 11
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: 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 12
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: 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 13
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: 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 14
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: 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 15
Project: Lie_to_me   Author: Notabela   File: thinkdsp.py    License: 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 16
Project: predictive-maintenance-using-machine-learning   Author: awslabs   File: tile.py    License: 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 17
Project: openscm   Author: openscm   File: test_core.py    License: 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 18
Project: robotics-rl-srl   Author: araffin   File: marker_render.py    License: 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 19
Project: ImageFusion   Author: pfchai   File: test_umath.py    License: 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 20
Project: Splunking-Crime   Author: nccgroup   File: tile.py    License: 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 21
Project: elasticintel   Author: securityclippy   File: tile.py    License: 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 22
Project: bifrost   Author: ledatelescope   File: block.py    License: 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 23
Project: Carnets   Author: holzschu   File: utils.py    License: 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 24
Project: Carnets   Author: holzschu   File: angle_utilities.py    License: 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 25
Project: Carnets   Author: holzschu   File: angle_utilities.py    License: 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 26
Project: Carnets   Author: holzschu   File: test_quantity_ufuncs.py    License: 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 27
Project: Carnets   Author: holzschu   File: test_quantity_ufuncs.py    License: 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 28
Project: keras-lambda   Author: sunilmallya   File: test_umath.py    License: 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 29
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 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
Project: mars   Author: mars-project   File: modf.py    License: Apache License 2.0 4 votes vote down vote up
def modf(x, out1=None, out2=None, out=None, where=None, **kwargs):
    """
    Return the fractional and integral parts of a tensor, element-wise.

    The fractional and integral parts are negative if the given number is
    negative.

    Parameters
    ----------
    x : array_like
        Input tensor.
    out : Tensor, None, or tuple of Tensor and None, optional
        A location into which the result is stored. If provided, it must have
        a shape that the inputs broadcast to. If not provided or `None`,
        a freshly-allocated tensor is returned. A tuple (possible only as a
        keyword argument) must have length equal to the number of outputs.
    where : array_like, optional
        Values of True indicate to calculate the ufunc at that position, values
        of False indicate to leave the value in the output alone.
    **kwargs

    Returns
    -------
    y1 : Tensor
        Fractional part of `x`.
    y2 : Tensor
        Integral part of `x`.

    Notes
    -----
    For integer input the return values are floats.

    See Also
    --------
    divmod : ``divmod(x, 1)`` is equivalent to ``modf`` with the return values
             switched, except it always has a positive remainder.

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

    >>> mt.modf([0, 3.5]).execute()
    (array([ 0. ,  0.5]), array([ 0.,  3.]))
    >>> mt.modf(-0.5).execute()
    (-0.5, -0)
    """
    x = astensor(x)
    op = TensorModf(**kwargs)
    return op(x, out1=out1, out2=out2, out=out, where=where)