~ubuntu-branches/ubuntu/feisty/python-numpy/feisty

« back to all changes in this revision

Viewing changes to numpy/core/tests/test_numerictypes.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2006-07-12 10:00:24 UTC
  • Revision ID: james.westby@ubuntu.com-20060712100024-5lw9q2yczlisqcrt
Tags: upstream-0.9.8
ImportĀ upstreamĀ versionĀ 0.9.8

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import sys
 
2
from numpy.testing import *
 
3
import numpy
 
4
from numpy import zeros, ones, array
 
5
 
 
6
 
 
7
# This is the structure of the table used for plain objects:
 
8
#
 
9
# +-+-+-+
 
10
# |x|y|z|
 
11
# +-+-+-+
 
12
 
 
13
# Structure of a plain array description:
 
14
Pdescr = [
 
15
    ('x', 'i4', (2,)),
 
16
    ('y', 'f8', (2, 2)),
 
17
    ('z', 'u1')]
 
18
 
 
19
# A plain list of tuples with values for testing:
 
20
PbufferT = [
 
21
    # x     y                  z
 
22
    ([3,2], [[6.,4.],[6.,4.]], 8),
 
23
    ([4,3], [[7.,5.],[7.,5.]], 9),
 
24
    ]
 
25
 
 
26
 
 
27
# This is the structure of the table used for nested objects (DON'T PANIC!):
 
28
#
 
29
# +-+---------------------------------+-----+----------+-+-+
 
30
# |x|Info                             |color|info      |y|z|
 
31
# | +-----+--+----------------+----+--+     +----+-----+ | |
 
32
# | |value|y2|Info2           |name|z2|     |Name|Value| | |
 
33
# | |     |  +----+-----+--+--+    |  |     |    |     | | |
 
34
# | |     |  |name|value|y3|z3|    |  |     |    |     | | |
 
35
# +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+
 
36
#
 
37
 
 
38
# The corresponding nested array description:
 
39
Ndescr = [
 
40
    ('x', 'i4', (2,)),
 
41
    ('Info', [
 
42
        ('value', 'c16'),
 
43
        ('y2', 'f8'),
 
44
        ('Info2', [
 
45
            ('name', 'S2'),
 
46
            ('value', 'c16', (2,)),
 
47
            ('y3', 'f8', (2,)),
 
48
            ('z3', 'u4', (2,))]),
 
49
        ('name', 'S2'),
 
50
        ('z2', 'b1')]),
 
51
    ('color', 'S2'),
 
52
    ('info', [
 
53
        ('Name', 'U8'),  # Try out 'U8' when interpretation of Unicode strings is more clear
 
54
        ('Value', 'c16')]),
 
55
    ('y', 'f8', (2, 2)),
 
56
    ('z', 'u1')]
 
57
 
 
58
NbufferT = [
 
59
    # x     Info                                                color info        y                  z
 
60
    #       value y2 Info2                            name z2         Name Value
 
61
    #                name   value    y3       z3
 
62
    ([3,2], (6j, 6., ('nn', [6j,4j], [6.,4.], [1,2]), 'NN', True), 'cc', ('NN', 6j), [[6.,4.],[6.,4.]], 8),
 
63
    ([4,3], (7j, 7., ('oo', [7j,5j], [7.,5.], [2,1]), 'OO', False), 'dd', ('OO', 7j), [[7.,5.],[7.,5.]], 9),
 
64
    ]
 
65
 
 
66
 
 
67
byteorder = {'little':'<', 'big':'>'}[sys.byteorder]
 
68
 
 
69
def normalize_descr(descr):
 
70
    "Normalize a description adding the platform byteorder."
 
71
 
 
72
    out = []
 
73
    for item in descr:
 
74
        dtype = item[1]
 
75
        if isinstance(dtype, str):
 
76
            if dtype[0] not in ['|','<','>']:
 
77
                onebyte = dtype[1:] == "1"
 
78
                if onebyte or dtype[0] in ['S', 'V', 'b']:
 
79
                    dtype = "|" + dtype
 
80
                else:
 
81
                    dtype = byteorder + dtype
 
82
            if len(item) > 2 and item[2] > 1:
 
83
                nitem = (item[0], dtype, item[2])
 
84
            else:
 
85
                nitem = (item[0], dtype)
 
86
            out.append(nitem)
 
87
        elif isinstance(item[1], list):
 
88
            l = []
 
89
            for j in normalize_descr(item[1]):
 
90
                l.append(j)
 
91
            out.append((item[0], l))
 
92
        else:
 
93
            raise ValueError("Expected a str or list and got %s" % \
 
94
                             (type(item)))
 
95
    return out
 
96
 
 
97
 
 
98
############################################################
 
99
#    Creation tests
 
100
############################################################
 
101
 
 
102
class create_zeros:
 
103
    """Check the creation of heterogeneous arrays zero-valued"""
 
104
 
 
105
    def check_zeros0D(self):
 
106
        """Check creation of 0-dimensional objects"""
 
107
        h = zeros((), dtype=self._descr)
 
108
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
109
        self.assert_(h.dtype.fields['x'][0].name[:4] == 'void')
 
110
        self.assert_(h.dtype.fields['x'][0].char == 'V')
 
111
        self.assert_(h.dtype.fields['x'][0].type == numpy.void)
 
112
        # A small check that data is ok
 
113
        assert_equal(h['z'], zeros((), dtype='u1'))
 
114
 
 
115
    def check_zerosSD(self):
 
116
        """Check creation of single-dimensional objects"""
 
117
        h = zeros((2,), dtype=self._descr)
 
118
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
119
        self.assert_(h.dtype['y'].name[:4] == 'void')
 
120
        self.assert_(h.dtype['y'].char == 'V')
 
121
        self.assert_(h.dtype['y'].type == numpy.void)
 
122
        # A small check that data is ok
 
123
        assert_equal(h['z'], zeros((2,), dtype='u1'))
 
124
 
 
125
    def check_zerosMD(self):
 
126
        """Check creation of multi-dimensional objects"""
 
127
        h = zeros((2,3), dtype=self._descr)
 
128
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
129
        self.assert_(h.dtype['z'].name == 'uint8')
 
130
        self.assert_(h.dtype['z'].char == 'B')
 
131
        self.assert_(h.dtype['z'].type == numpy.uint8)
 
132
        # A small check that data is ok
 
133
        assert_equal(h['z'], zeros((2,3), dtype='u1'))
 
134
 
 
135
 
 
136
class test_create_zeros_plain(create_zeros, NumpyTestCase):
 
137
    """Check the creation of heterogeneous arrays zero-valued (plain)"""
 
138
    _descr = Pdescr
 
139
 
 
140
class test_create_zeros_nested(create_zeros, NumpyTestCase):
 
141
    """Check the creation of heterogeneous arrays zero-valued (nested)"""
 
142
    _descr = Ndescr
 
143
 
 
144
 
 
145
class create_values:
 
146
    """Check the creation of heterogeneous arrays with values"""
 
147
 
 
148
    def check_tuple(self):
 
149
        """Check creation from tuples"""
 
150
        h = array(self._buffer, dtype=self._descr)
 
151
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
152
        if self.multiple_rows:
 
153
            self.assert_(h.shape == (2,))
 
154
        else:
 
155
            self.assert_(h.shape == ())
 
156
 
 
157
    def check_list_of_tuple(self):
 
158
        """Check creation from list of tuples"""
 
159
        h = array([self._buffer], dtype=self._descr)
 
160
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
161
        if self.multiple_rows:
 
162
            self.assert_(h.shape == (1,2))
 
163
        else:
 
164
            self.assert_(h.shape == (1,))
 
165
 
 
166
    def check_list_of_list_of_tuple(self):
 
167
        """Check creation from list of list of tuples"""
 
168
        h = array([[self._buffer]], dtype=self._descr)
 
169
        self.assert_(normalize_descr(self._descr) == h.dtype.descr)
 
170
        if self.multiple_rows:
 
171
            self.assert_(h.shape == (1,1,2))
 
172
        else:
 
173
            self.assert_(h.shape == (1,1))
 
174
 
 
175
 
 
176
class test_create_values_plain_single(create_values, NumpyTestCase):
 
177
    """Check the creation of heterogeneous arrays (plain, single row)"""
 
178
    _descr = Pdescr
 
179
    multiple_rows = 0
 
180
    _buffer = PbufferT[0]
 
181
 
 
182
class test_create_values_plain_multiple(create_values, NumpyTestCase):
 
183
    """Check the creation of heterogeneous arrays (plain, multiple rows)"""
 
184
    _descr = Pdescr
 
185
    multiple_rows = 1
 
186
    _buffer = PbufferT
 
187
 
 
188
class test_create_values_nested_single(create_values, NumpyTestCase):
 
189
    """Check the creation of heterogeneous arrays (nested, single row)"""
 
190
    _descr = Ndescr
 
191
    multiple_rows = 0
 
192
    _buffer = NbufferT[0]
 
193
 
 
194
class test_create_values_nested_multiple(create_values, NumpyTestCase):
 
195
    """Check the creation of heterogeneous arrays (nested, multiple rows)"""
 
196
    _descr = Ndescr
 
197
    multiple_rows = 1
 
198
    _buffer = NbufferT
 
199
 
 
200
 
 
201
############################################################
 
202
#    Reading tests
 
203
############################################################
 
204
 
 
205
class read_values_plain:
 
206
    """Check the reading of values in heterogeneous arrays (plain)"""
 
207
 
 
208
    def check_access_fields(self):
 
209
        h = array(self._buffer, dtype=self._descr)
 
210
        if not self.multiple_rows:
 
211
            self.assert_(h.shape == ())
 
212
            assert_equal(h['x'], array(self._buffer[0], dtype='i4'))
 
213
            assert_equal(h['y'], array(self._buffer[1], dtype='f8'))
 
214
            assert_equal(h['z'], array(self._buffer[2], dtype='u1'))
 
215
        else:
 
216
            self.assert_(len(h) == 2)
 
217
            assert_equal(h['x'], array([self._buffer[0][0],
 
218
                                             self._buffer[1][0]], dtype='i4'))
 
219
            assert_equal(h['y'], array([self._buffer[0][1],
 
220
                                             self._buffer[1][1]], dtype='f8'))
 
221
            assert_equal(h['z'], array([self._buffer[0][2],
 
222
                                             self._buffer[1][2]], dtype='u1'))
 
223
 
 
224
 
 
225
class test_read_values_plain_single(read_values_plain, NumpyTestCase):
 
226
    """Check the creation of heterogeneous arrays (plain, single row)"""
 
227
    _descr = Pdescr
 
228
    multiple_rows = 0
 
229
    _buffer = PbufferT[0]
 
230
 
 
231
class test_read_values_plain_multiple(read_values_plain, NumpyTestCase):
 
232
    """Check the values of heterogeneous arrays (plain, multiple rows)"""
 
233
    _descr = Pdescr
 
234
    multiple_rows = 1
 
235
    _buffer = PbufferT
 
236
 
 
237
class read_values_nested:
 
238
    """Check the reading of values in heterogeneous arrays (nested)"""
 
239
 
 
240
 
 
241
    def check_access_top_fields(self):
 
242
        """Check reading the top fields of a nested array"""
 
243
        h = array(self._buffer, dtype=self._descr)
 
244
        if not self.multiple_rows:
 
245
            self.assert_(h.shape == ())
 
246
            assert_equal(h['x'], array(self._buffer[0], dtype='i4'))
 
247
            assert_equal(h['y'], array(self._buffer[4], dtype='f8'))
 
248
            assert_equal(h['z'], array(self._buffer[5], dtype='u1'))
 
249
        else:
 
250
            self.assert_(len(h) == 2)
 
251
            assert_equal(h['x'], array([self._buffer[0][0],
 
252
                                             self._buffer[1][0]], dtype='i4'))
 
253
            assert_equal(h['y'], array([self._buffer[0][4],
 
254
                                             self._buffer[1][4]], dtype='f8'))
 
255
            assert_equal(h['z'], array([self._buffer[0][5],
 
256
                                             self._buffer[1][5]], dtype='u1'))
 
257
 
 
258
 
 
259
    def check_nested1_acessors(self):
 
260
        """Check reading the nested fields of a nested array (1st level)"""
 
261
        h = array(self._buffer, dtype=self._descr)
 
262
        if not self.multiple_rows:
 
263
            assert_equal(h['Info']['value'],
 
264
                         array(self._buffer[1][0], dtype='c16'))
 
265
            assert_equal(h['Info']['y2'],
 
266
                         array(self._buffer[1][1], dtype='f8'))
 
267
            assert_equal(h['info']['Name'],
 
268
                         array(self._buffer[3][0], dtype='U2'))
 
269
            assert_equal(h['info']['Value'],
 
270
                         array(self._buffer[3][1], dtype='c16'))
 
271
        else:
 
272
            assert_equal(h['Info']['value'],
 
273
                         array([self._buffer[0][1][0],
 
274
                                self._buffer[1][1][0]],
 
275
                                dtype='c16'))
 
276
            assert_equal(h['Info']['y2'],
 
277
                         array([self._buffer[0][1][1],
 
278
                                self._buffer[1][1][1]],
 
279
                                dtype='f8'))
 
280
            assert_equal(h['info']['Name'],
 
281
                         array([self._buffer[0][3][0],
 
282
                                self._buffer[1][3][0]],
 
283
                               dtype='U2'))
 
284
            assert_equal(h['info']['Value'],
 
285
                         array([self._buffer[0][3][1],
 
286
                                self._buffer[1][3][1]],
 
287
                               dtype='c16'))
 
288
 
 
289
    def check_nested2_acessors(self):
 
290
        """Check reading the nested fields of a nested array (2nd level)"""
 
291
        h = array(self._buffer, dtype=self._descr)
 
292
        if not self.multiple_rows:
 
293
            assert_equal(h['Info']['Info2']['value'],
 
294
                         array(self._buffer[1][2][1], dtype='c16'))
 
295
            assert_equal(h['Info']['Info2']['z3'],
 
296
                         array(self._buffer[1][2][3], dtype='u4'))
 
297
        else:
 
298
            assert_equal(h['Info']['Info2']['value'],
 
299
                         array([self._buffer[0][1][2][1],
 
300
                                self._buffer[1][1][2][1]],
 
301
                               dtype='c16'))
 
302
            assert_equal(h['Info']['Info2']['z3'],
 
303
                         array([self._buffer[0][1][2][3],
 
304
                                self._buffer[1][1][2][3]],
 
305
                               dtype='u4'))
 
306
 
 
307
    def check_nested1_descriptor(self):
 
308
        """Check access nested descriptors of a nested array (1st level)"""
 
309
        h = array(self._buffer, dtype=self._descr)
 
310
        self.assert_(h.dtype['Info']['value'].name == 'complex128')
 
311
        self.assert_(h.dtype['Info']['y2'].name == 'float64')
 
312
        self.assert_(h.dtype['info']['Name'].name == 'unicode256')
 
313
        self.assert_(h.dtype['info']['Value'].name == 'complex128')
 
314
 
 
315
    def check_nested2_descriptor(self):
 
316
        """Check access nested descriptors of a nested array (2nd level)"""
 
317
        h = array(self._buffer, dtype=self._descr)
 
318
        self.assert_(h.dtype['Info']['Info2']['value'].name == 'void256')
 
319
        self.assert_(h.dtype['Info']['Info2']['z3'].name == 'void64')
 
320
 
 
321
 
 
322
class test_read_values_nested_single(read_values_nested, NumpyTestCase):
 
323
    """Check the values of heterogeneous arrays (nested, single row)"""
 
324
    _descr = Ndescr
 
325
    multiple_rows = 0
 
326
    _buffer = NbufferT[0]
 
327
 
 
328
class test_read_values_nested_multiple(read_values_nested, NumpyTestCase):
 
329
    """Check the values of heterogeneous arrays (nested, multiple rows)"""
 
330
    _descr = Ndescr
 
331
    multiple_rows = 1
 
332
    _buffer = NbufferT
 
333
 
 
334
 
 
335
if __name__ == "__main__":
 
336
    NumpyTest().run()