Python numpy.get_printoptions() Examples

The following are 30 code examples of numpy.get_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: test_core.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #2
Source File: logger.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def pformat(obj, indent=0, depth=3):
    if 'numpy' in sys.modules:
        import numpy as np
        print_options = np.get_printoptions()
        np.set_printoptions(precision=6, threshold=64, edgeitems=1)
    else:
        print_options = None
    out = pprint.pformat(obj, depth=depth, indent=indent)
    if print_options:
        np.set_printoptions(**print_options)
    return out


###############################################################################
# class `Logger`
############################################################################### 
Example #3
Source File: hinton.py    From PRPN with MIT License 6 votes vote down vote up
def plot(arr, max_val=None):
    if max_val is None:
        max_arr = arr
        max_val = max(abs(np.max(max_arr)), abs(np.min(max_arr)))

    opts = np.get_printoptions()
    np.set_printoptions(edgeitems=500)
    s = str(np.array2string(arr,
                          formatter={
                              'float_kind': lambda x: visual(x, max_val),
                              'int_kind': lambda x: visual(x, max_val)},
                          max_line_width=5000
                          ))
    np.set_printoptions(**opts)

    return s 
Example #4
Source File: hinton.py    From PRPN-Analysis with MIT License 6 votes vote down vote up
def plot(arr, max_val=None):
    if max_val is None:
        max_arr = arr
        max_val = max(abs(np.max(max_arr)), abs(np.min(max_arr)))

    opts = np.get_printoptions()
    np.set_printoptions(edgeitems=500)
    s = str(np.array2string(arr,
                          formatter={
                              'float_kind': lambda x: visual(x, max_val),
                              'int_kind': lambda x: visual(x, max_val)},
                          max_line_width=5000
                          ))
    np.set_printoptions(**opts)

    return s 
Example #5
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 #6
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 #7
Source File: hinton.py    From Ordered-Memory with MIT License 6 votes vote down vote up
def plot(arr, max_val=None):
    if max_val is None:
        max_arr = arr
        max_val = max(abs(np.max(max_arr)), abs(np.min(max_arr)))

    opts = np.get_printoptions()
    np.set_printoptions(edgeitems=500)
    fig = np.array2string(arr,
                          formatter={
                              'float_kind': lambda x: visual(x, max_val),
                              'int_kind': lambda x: visual(x, max_val)},
                          max_line_width=5000
                          )
    np.set_printoptions(**opts)

    return fig 
Example #8
Source File: basic_session_run_hooks.py    From lambda-packs with MIT License 6 votes vote down vote up
def after_run(self, run_context, run_values):
    _ = run_context
    if self._should_trigger:
      original = np.get_printoptions()
      np.set_printoptions(suppress=True)
      elapsed_secs, _ = self._timer.update_last_triggered_step(self._iter_count)
      if self._formatter:
        logging.info(self._formatter(run_values.results))
      else:
        stats = []
        for tag in self._tag_order:
          stats.append("%s = %s" % (tag, run_values.results[tag]))
        if elapsed_secs is not None:
          logging.info("%s (%.3f sec)", ", ".join(stats), elapsed_secs)
        else:
          logging.info("%s", ", ".join(stats))
      np.set_printoptions(**original)
    self._iter_count += 1 
Example #9
Source File: logger.py    From mlens with MIT License 6 votes vote down vote up
def pformat(obj, indent=0, depth=3):
    if 'numpy' in sys.modules:
        import numpy as np
        print_options = np.get_printoptions()
        np.set_printoptions(precision=6, threshold=64, edgeitems=1)
    else:
        print_options = None
    out = pprint.pformat(obj, depth=depth, indent=indent)
    if print_options:
        np.set_printoptions(**print_options)
    return out


###############################################################################
# class `Logger`
############################################################################### 
Example #10
Source File: test_core.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #11
Source File: np_util.py    From leap with MIT License 6 votes vote down vote up
def np_print_options(*args, **kwargs):
    """
    Locally modify print behavior.

    Usage:
    ```
    x = np.random.random(10)
    with printoptions(precision=3, suppress=True):
        print(x)
        # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]
    ```

    http://stackoverflow.com/questions/2891790/how-to-pretty-printing-a-numpy-array-without-scientific-notation-and-with-given
    :param args:
    :param kwargs:
    :return:
    """
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    yield
    np.set_printoptions(**original)


# TODO(vpong): Test this 
Example #12
Source File: test_core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #13
Source File: test_core.py    From pySINDy with MIT License 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #14
Source File: test_core.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #15
Source File: test_findiff.py    From findiff with MIT License 6 votes vote down vote up
def test_matrix_2d(self):
        thr = np.get_printoptions()["threshold"]
        lw = np.get_printoptions()["linewidth"]
        np.set_printoptions(threshold=np.inf)
        np.set_printoptions(linewidth=500)
        x, y = [np.linspace(0, 4, 5)] * 2
        X, Y = np.meshgrid(x, y, indexing='ij')
        laplace = FinDiff(0, x[1]-x[0], 2) + FinDiff(0, y[1]-y[0], 2)
        #d = FinDiff(1, y[1]-y[0], 2)
        u = X**2 + Y**2

        mat = laplace.matrix(u.shape)

        np.testing.assert_array_almost_equal(4 * np.ones_like(X).reshape(-1), mat.dot(u.reshape(-1)))

        np.set_printoptions(threshold=thr)
        np.set_printoptions(linewidth=lw) 
Example #16
Source File: test_core.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_str_repr_legacy(self):
        oldopts = np.get_printoptions()
        np.set_printoptions(legacy='1.13')
        try:
            a = array([0, 1, 2], mask=[False, True, False])
            assert_equal(str(a), '[0 -- 2]')
            assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
                                  '             mask = [False  True False],\n'
                                  '       fill_value = 999999)\n')

            a = np.ma.arange(2000)
            a[1:50] = np.ma.masked
            assert_equal(
                repr(a),
                'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
                '             mask = [False  True  True ..., False False False],\n'
                '       fill_value = 999999)\n'
            )
        finally:
            np.set_printoptions(**oldopts) 
Example #17
Source File: variable_logger_hook.py    From tensor2robot with Apache License 2.0 5 votes vote down vote up
def after_run(self, run_context, run_values):
    del run_context
    original = np.get_printoptions()
    np.set_printoptions(suppress=True)
    for variable, variable_value in zip(self._variables_to_log,
                                        run_values.results):
      if not isinstance(variable_value, np.ndarray):
        continue
      variable_value = variable_value.ravel()
      logging.info('%s.mean = %s', variable.op.name, np.mean(variable_value))
      logging.info('%s.std = %s', variable.op.name, np.std(variable_value))
      if self._max_num_variable_values:
        variable_value = variable_value[:self._max_num_variable_values]
      logging.info('%s = %s', variable.op.name, variable_value)
    np.set_printoptions(**original) 
Example #18
Source File: inspect_checkpoint.py    From MobileNet with Apache License 2.0 5 votes vote down vote up
def parse_numpy_printoption(kv_str):
    """Sets a single numpy printoption from a string of the form 'x=y'.

    See documentation on numpy.set_printoptions() for details about what values
    x and y can take. x can be any option listed there other than 'formatter'.

    Args:
        kv_str: A string of the form 'x=y', such as 'threshold=100000'

    Raises:
        argparse.ArgumentTypeError: If the string couldn't be used to set any
                nump printoption.
    """
    k_v_str = kv_str.split("=", 1)
    if len(k_v_str) != 2 or not k_v_str[0]:
        raise argparse.ArgumentTypeError("'%s' is not in the form k=v." % kv_str)
    k, v_str = k_v_str
    printoptions = np.get_printoptions()
    if k not in printoptions:
        raise argparse.ArgumentTypeError("'%s' is not a valid printoption." % k)
    v_type = type(printoptions[k])
    if v_type is type(None):
        raise argparse.ArgumentTypeError(
                "Setting '%s' from the command line is not supported." % k)
    try:
        v = (v_type(v_str) if v_type is not bool
             else flags.BooleanParser().Parse(v_str))
    except ValueError as e:
        raise argparse.ArgumentTypeError(e.message)
    np.set_printoptions(**{k: v}) 
Example #19
Source File: utils.py    From MultiPlanarUNet with MIT License 5 votes vote down vote up
def print_options_context(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    try:
        yield
    finally:
        np.set_printoptions(**original) 
Example #20
Source File: sample_pulse.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def __repr__(self) -> str:
        opt = np.get_printoptions()
        np.set_printoptions(threshold=50)
        np.set_printoptions(**opt)
        return "{}({}{})".format(self.__class__.__name__, repr(self.samples),
                                 ", name='{}'".format(self.name) if self.name is not None else "") 
Example #21
Source File: valuesummarymeter.py    From midlevel-reps with MIT License 5 votes vote down vote up
def __str__(self): 
        old_po = np.get_printoptions()
        np.set_printoptions(precision=3)
        res = "mean(std) {} ({}) \tmin/max {}/{}\t".format(
            *[np.array(v) for v in [self.mean, self.std, self.min, self.max]])
        np.set_printoptions(**old_po)
        return res 
Example #22
Source File: util.py    From kernel-gof with MIT License 5 votes vote down vote up
def fullprint(*args, **kwargs):
    "https://gist.github.com/ZGainsforth/3a306084013633c52881"
    from pprint import pprint
    import numpy
    opt = numpy.get_printoptions()
    numpy.set_printoptions(threshold='nan')
    pprint(*args, **kwargs)
    numpy.set_printoptions(**opt) 
Example #23
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_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 #24
Source File: test_arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def setup(self):
        self.oldopts = np.get_printoptions() 
Example #25
Source File: arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 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 #26
Source File: arrayprint.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def get_printoptions():
    """
    Return the current print options.

    Returns
    -------
    print_opts : dict
        Dictionary of current print options with keys

          - precision : int
          - threshold : int
          - edgeitems : int
          - linewidth : int
          - suppress : bool
          - nanstr : str
          - infstr : str
          - formatter : dict of callables
          - sign : str

        For a full description of these options, see `set_printoptions`.

    See Also
    --------
    set_printoptions, set_string_function

    """
    return _format_options.copy() 
Example #27
Source File: test_arrayprint.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.oldopts = np.get_printoptions() 
Example #28
Source File: test_arrayprint.py    From GraphicDesignPatternByPython 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 #29
Source File: test_arrayprint.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def setup(self):
        self.oldopts = np.get_printoptions() 
Example #30
Source File: arrayprint.py    From GraphicDesignPatternByPython 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)