Пример #1
0
 def test_basic(self):
     """Basic test of array2string."""
     a = np.arange(3)
     assert_(np.array2string(a) == '[0 1 2]')
     assert_(
         np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]')
     assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
Пример #2
0
 def test_refcount(self):
     # make sure we do not hold references to the array due to a recursive
     # closure (gh-10620)
     gc.disable()
     a = np.arange(2)
     r1 = sys.getrefcount(a)
     np.array2string(a)
     np.array2string(a)
     r2 = sys.getrefcount(a)
     gc.collect()
     gc.enable()
     assert_(r1 == r2)
Пример #3
0
    def test_format_function(self):
        """Test custom format function for each element in array."""
        def _format_function(x):
            if np.abs(x) < 1:
                return '.'
            elif np.abs(x) < 2:
                return 'o'
            else:
                return 'O'

        x = np.arange(3)
        if sys.version_info[0] >= 3:
            x_hex = "[0x0 0x1 0x2]"
            x_oct = "[0o0 0o1 0o2]"
        else:
            x_hex = "[0x0L 0x1L 0x2L]"
            x_oct = "[0L 01L 02L]"
        assert_(
            np.array2string(x, formatter={'all': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'int_kind': _format_function}) ==
            "[. o O]")
        assert_(
            np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) ==
            "[0.0000 1.0000 2.0000]")
        assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}),
                     x_hex)
        assert_equal(np.array2string(x, formatter={'int': lambda x: oct(x)}),
                     x_oct)

        x = np.arange(3.)
        assert_(
            np.array2string(x, formatter={'float_kind': lambda x: "%.2f" % x})
            == "[0.00 1.00 2.00]")
        assert_(
            np.array2string(x, formatter={'float': lambda x: "%.2f" % x}) ==
            "[0.00 1.00 2.00]")

        s = np.array(['abc', 'def'])
        assert_(
            np.array2string(s, formatter={'numpystr': lambda s: s * 2}) ==
            '[abcabc defdef]')

        # check for backcompat that using FloatFormat works and emits warning
        with assert_warns(DeprecationWarning):
            fmt = np.core.arrayprint.FloatFormat(x, 9, 'maxprec', False)
        assert_equal(np.array2string(x, formatter={'float_kind': fmt}),
                     '[0. 1. 2.]')
Пример #4
0
    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')
Пример #5
0
    def test_structure_format(self):
        dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2, ))])
        x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
        assert_equal(np.array2string(x),
                     "[('Sarah', [8., 7.]) ('John', [6., 7.])]")

        np.set_printoptions(legacy='1.13')
        try:
            # for issue #5692
            A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
            A[5:].fill(np.datetime64('NaT'))
            assert_equal(
                np.array2string(A),
                textwrap.dedent("""\
                [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
                 ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('NaT',) ('NaT',)
                 ('NaT',) ('NaT',) ('NaT',)]"""))
        finally:
            np.set_printoptions(legacy=False)

        # same again, but with non-legacy behavior
        assert_equal(
            np.array2string(A),
            textwrap.dedent("""\
            [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
             ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
             ('1970-01-01T00:00:00',) (                'NaT',)
             (                'NaT',) (                'NaT',)
             (                'NaT',) (                'NaT',)]"""))

        # and again, with timedeltas
        A = np.full(10, 123456, dtype=[("A", "m8[s]")])
        A[5:].fill(np.datetime64('NaT'))
        assert_equal(
            np.array2string(A),
            textwrap.dedent("""\
            [(123456,) (123456,) (123456,) (123456,) (123456,) ( 'NaT',) ( 'NaT',)
             ( 'NaT',) ( 'NaT',) ( 'NaT',)]"""))

        # See #8160
        struct_int = np.array([([1, -1], ), ([123, 1], )],
                              dtype=[('B', 'i4', 2)])
        assert_equal(np.array2string(struct_int),
                     "[([  1,  -1],) ([123,   1],)]")
        struct_2dint = np.array([([[0, 1], [2, 3]], ), ([[12, 0], [0, 0]], )],
                                dtype=[('B', 'i4', (2, 2))])
        assert_equal(np.array2string(struct_2dint),
                     "[([[ 0,  1], [ 2,  3]],) ([[12,  0], [ 0,  0]],)]")

        # See #8172
        array_scalar = np.array((1., 2.1234567890123456789, 3.),
                                dtype=('f8,f8,f8'))
        assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
Пример #6
0
 def test_wide_element(self):
     a = np.array(['xxxxx'])
     assert_equal(np.array2string(a, max_line_width=5), "['xxxxx']")
     assert_equal(np.array2string(a, max_line_width=5, legacy='1.13'),
                  "[ 'xxxxx']")
Пример #7
0
 def make_str(a, width, **kw):
     return np.array2string(a, separator="", max_line_width=width, **kw)
Пример #8
0
 def test_edgeitems_kwarg(self):
     # previously the global print options would be taken over the kwarg
     arr = np.zeros(3, int)
     assert_equal(np.array2string(arr, edgeitems=1, threshold=0),
                  "[0 ... 0]")
Пример #9
0
 def __str__(self):
     if self.shape == ():
         return self.to_string()
     else:
         fmt = {'all': lambda x: x.to_string()}
         return np.array2string(self, formatter=fmt)