Python numpy.printoptions() Examples

The following are 30 code examples of numpy.printoptions(). 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: core.py    From mars with Apache License 2.0 6 votes vote down vote up
def _to_str(self, representation=False):
        if build_mode().is_build_mode or len(self._executed_sessions) == 0:
            # in build mode, or not executed, just return representation
            if representation:
                return 'Tensor <op={}, shape={}, key={}'.format(self._op.__class__.__name__,
                                                                self._shape,
                                                                self._key)
            else:
                return 'Tensor(op={}, shape={})'.format(self._op.__class__.__name__,
                                                        self._shape)
        else:
            print_options = np.get_printoptions()
            threshold = print_options['threshold']

            corner_data = fetch_corner_data(self, session=self._executed_sessions[-1])
            # if less than default threshold, just set it as default,
            # if not, set to corner_data.size - 1 make sure ... exists in repr
            threshold = threshold if self.size <= threshold else corner_data.size - 1
            with np.printoptions(threshold=threshold):
                corner_str = repr(corner_data) if representation else str(corner_data)
            return corner_str 
Example #2
Source File: test_utils.py    From mars with Apache License 2.0 6 votes vote down vote up
def testFetchTensorCornerData(self):
        sess = new_session()
        print_options = np.get_printoptions()

        # make sure numpy default option
        self.assertEqual(print_options['edgeitems'], 3)
        self.assertEqual(print_options['threshold'], 1000)

        size = 12
        for i in (2, 4, size - 3, size, size + 3):
            arr = np.random.rand(i, i, i)
            t = mt.tensor(arr, chunk_size=size // 2)
            sess.run(t, fetch=False)

            corner_data = fetch_corner_data(t, session=sess)
            corner_threshold = 1000 if t.size < 1000 else corner_data.size - 1
            with np.printoptions(threshold=corner_threshold, suppress=True):
                # when we repr corner data, we need to limit threshold that
                # it's exactly less than the size
                repr_corner_data = repr(corner_data)
            with np.printoptions(suppress=True):
                repr_result = repr(arr)
            self.assertEqual(repr_corner_data, repr_result,
                             'failed when size == {}'.format(i)) 
Example #3
Source File: states.py    From fragile with MIT License 6 votes vote down vote up
def __repr__(self):
        with numpy.printoptions(linewidth=100, threshold=200, edgeitems=9):
            string = (
                "reward: %s\n"
                "time: %s\n"
                "observ: %s\n"
                "state: %s\n"
                "id: %s"
                % (
                    self.rewards[0],
                    self.times[0],
                    self.observs[0].flatten(),
                    self.states[0].flatten(),
                    self.id_walkers[0],
                )
            )
            return string 
Example #4
Source File: arrayprint.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def printoptions(*args, **kwargs):
    """Context manager for setting print options.

    Set print options for the scope of the `with` block, and restore the old
    options at the end. See `set_printoptions` for the full description of
    available options.

    Examples
    --------

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0])) / 3
    [0.67]

    The `as`-clause of the `with`-statement gives the current print options:

    >>> with np.printoptions(precision=2) as opts:
    ...      assert_equal(opts, np.get_printoptions())

    See Also
    --------
    set_printoptions, get_printoptions

    """
    opts = np.get_printoptions()
    try:
        np.set_printoptions(*args, **kwargs)
        yield np.get_printoptions()
    finally:
        np.set_printoptions(**opts) 
Example #5
Source File: arrayprint.py    From pySINDy with MIT License 5 votes vote down vote up
def printoptions(*args, **kwargs):
    """Context manager for setting print options.

    Set print options for the scope of the `with` block, and restore the old
    options at the end. See `set_printoptions` for the full description of
    available options.

    Examples
    --------

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0])) / 3
    [0.67]

    The `as`-clause of the `with`-statement gives the current print options:

    >>> with np.printoptions(precision=2) as opts:
    ...      assert_equal(opts, np.get_printoptions())

    See Also
    --------
    set_printoptions, get_printoptions

    """
    opts = np.get_printoptions()
    try:
        np.set_printoptions(*args, **kwargs)
        yield np.get_printoptions()
    finally:
        np.set_printoptions(**opts) 
Example #6
Source File: test_arrayprint.py    From pySINDy with MIT License 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example #7
Source File: test_arrayprint.py    From pySINDy with MIT License 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #8
Source File: test_arrayprint.py    From pySINDy with MIT License 5 votes vote down vote up
def test_ctx_mgr_restores(self):
        # test that print options are actually restrored
        opts = np.get_printoptions()
        with np.printoptions(precision=opts['precision'] - 1,
                             linewidth=opts['linewidth'] - 4):
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #9
Source File: test_arrayprint.py    From pySINDy with MIT License 5 votes vote down vote up
def test_ctx_mgr_exceptions(self):
        # test that print options are restored even if an exception is raised
        opts = np.get_printoptions()
        try:
            with np.printoptions(precision=2, linewidth=11):
                raise ValueError
        except ValueError:
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #10
Source File: arrayprint.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def printoptions(*args, **kwargs):
    """Context manager for setting print options.

    Set print options for the scope of the `with` block, and restore the old
    options at the end. See `set_printoptions` for the full description of
    available options.

    Examples
    --------

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0])) / 3
    [0.67]

    The `as`-clause of the `with`-statement gives the current print options:

    >>> with np.printoptions(precision=2) as opts:
    ...      assert_equal(opts, np.get_printoptions())

    See Also
    --------
    set_printoptions, get_printoptions

    """
    opts = np.get_printoptions()
    try:
        np.set_printoptions(*args, **kwargs)
        yield np.get_printoptions()
    finally:
        np.set_printoptions(**opts) 
Example #11
Source File: test_arrayprint.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example #12
Source File: test_arrayprint.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #13
Source File: test_arrayprint.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_ctx_mgr_restores(self):
        # test that print options are actually restrored
        opts = np.get_printoptions()
        with np.printoptions(precision=opts['precision'] - 1,
                             linewidth=opts['linewidth'] - 4):
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #14
Source File: test_arrayprint.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_ctx_mgr_exceptions(self):
        # test that print options are restored even if an exception is raised
        opts = np.get_printoptions()
        try:
            with np.printoptions(precision=2, linewidth=11):
                raise ValueError
        except ValueError:
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #15
Source File: function_helpers.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def array2string(a, *args, **kwargs):
    # array2string breaks on quantities as it tries to turn individual
    # items into float, which works only for dimensionless.  Since the
    # defaults would not keep any unit anyway, this is rather pointless -
    # we're better off just passing on the array view.  However, one can
    # also work around this by passing on a formatter (as is done in Angle).
    # So, we do nothing if the formatter argument is present and has the
    # relevant formatter for our dtype.
    formatter = args[6] if len(args) >= 7 else kwargs.get('formatter', None)

    if formatter is None:
        a = a.value
    else:
        # See whether it covers our dtype.
        from numpy.core.arrayprint import _get_format_function

        with np.printoptions(formatter=formatter) as options:
            try:
                ff = _get_format_function(a.value, **options)
            except Exception:
                # Shouldn't happen, but possibly we're just not being smart
                # enough, so let's pass things on as is.
                pass
            else:
                # If the selected format function is that of numpy, we know
                # things will fail
                if 'numpy' in ff.__module__:
                    a = a.value

    return (a,) + args, kwargs, None, None 
Example #16
Source File: test_quantity_non_ufuncs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_wrapped_functions(*modules):
    wrapped_functions = {}
    for mod in modules:
        for name, f in mod.__dict__.items():
            if f is np.printoptions:
                continue
            if callable(f) and hasattr(f, '__wrapped__'):
                wrapped_functions[name] = f
    return wrapped_functions 
Example #17
Source File: arrayprint.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def printoptions(*args, **kwargs):
    """Context manager for setting print options.

    Set print options for the scope of the `with` block, and restore the old
    options at the end. See `set_printoptions` for the full description of
    available options.

    Examples
    --------

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0])) / 3
    [0.67]

    The `as`-clause of the `with`-statement gives the current print options:

    >>> with np.printoptions(precision=2) as opts:
    ...      assert_equal(opts, np.get_printoptions())

    See Also
    --------
    set_printoptions, get_printoptions

    """
    opts = np.get_printoptions()
    try:
        np.set_printoptions(*args, **kwargs)
        yield np.get_printoptions()
    finally:
        np.set_printoptions(**opts) 
Example #18
Source File: test_arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #19
Source File: test_arrayprint.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example #20
Source File: test_arrayprint.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #21
Source File: test_arrayprint.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def test_ctx_mgr_restores(self):
        # test that print options are actually restrored
        opts = np.get_printoptions()
        with np.printoptions(precision=opts['precision'] - 1,
                             linewidth=opts['linewidth'] - 4):
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #22
Source File: test_arrayprint.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def test_ctx_mgr_exceptions(self):
        # test that print options are restored even if an exception is raised
        opts = np.get_printoptions()
        try:
            with np.printoptions(precision=2, linewidth=11):
                raise ValueError
        except ValueError:
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #23
Source File: arrayprint.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def printoptions(*args, **kwargs):
    """Context manager for setting print options.

    Set print options for the scope of the `with` block, and restore the old
    options at the end. See `set_printoptions` for the full description of
    available options.

    Examples
    --------

    >>> with np.printoptions(precision=2):
    ...     print(np.array([2.0])) / 3
    [0.67]

    The `as`-clause of the `with`-statement gives the current print options:

    >>> with np.printoptions(precision=2) as opts:
    ...      assert_equal(opts, np.get_printoptions())

    See Also
    --------
    set_printoptions, get_printoptions

    """
    opts = np.get_printoptions()
    try:
        np.set_printoptions(*args, **kwargs)
        yield np.get_printoptions()
    finally:
        np.set_printoptions(**opts) 
Example #24
Source File: test_arrayprint.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example #25
Source File: test_arrayprint.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #26
Source File: test_arrayprint.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_ctx_mgr_restores(self):
        # test that print options are actually restrored
        opts = np.get_printoptions()
        with np.printoptions(precision=opts['precision'] - 1,
                             linewidth=opts['linewidth'] - 4):
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #27
Source File: test_arrayprint.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_ctx_mgr_exceptions(self):
        # test that print options are restored even if an exception is raised
        opts = np.get_printoptions()
        try:
            with np.printoptions(precision=2, linewidth=11):
                raise ValueError
        except ValueError:
            pass
        assert_equal(np.get_printoptions(), opts) 
Example #28
Source File: test_arrayprint.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]') 
Example #29
Source File: test_arrayprint.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_0d_arrays(self):
        unicode = type(u'')

        assert_equal(unicode(np.array(u'café', '<U4')), u'café')

        if sys.version_info[0] >= 3:
            assert_equal(repr(np.array('café', '<U4')),
                         "array('café', dtype='<U4')")
        else:
            assert_equal(repr(np.array(u'café', '<U4')),
                         "array(u'caf\\xe9', dtype='<U4')")
        assert_equal(str(np.array('test', np.str_)), 'test')

        a = np.zeros(1, dtype=[('a', '<i4', (3,))])
        assert_equal(str(a[0]), '([0, 0, 0],)')

        assert_equal(repr(np.datetime64('2005-02-25')[...]),
                     "array('2005-02-25', dtype='datetime64[D]')")

        assert_equal(repr(np.timedelta64('10', 'Y')[...]),
                     "array(10, dtype='timedelta64[Y]')")

        # repr of 0d arrays is affected by printoptions
        x = np.array(1)
        np.set_printoptions(formatter={'all':lambda x: "test"})
        assert_equal(repr(x), "array(test)")
        # str is unaffected
        assert_equal(str(x), "1")

        # check `style` arg raises
        assert_warns(DeprecationWarning, np.array2string,
                                         np.array(1.), style=repr)
        # but not in legacy mode
        np.array2string(np.array(1.), style=repr, legacy='1.13')
        # gh-10934 style was broken in legacy mode, check it works
        np.array2string(np.array(1.), legacy='1.13') 
Example #30
Source File: test_arrayprint.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_ctx_mgr(self):
        # test that context manager actuall works
        with np.printoptions(precision=2):
            s = str(np.array([2.0]) / 3)
        assert_equal(s, '[0.67]')