Debian Codegraph @

pypy/module/micronumpy/descriptor.py

raw symbols SCIP
1 import string
2 from pypy.interpreter.argument import Arguments
3 from pypy.interpreter.baseobjspace import W_Root
4 from pypy.interpreter.error import OperationError, oefmt
5 from pypy.interpreter.gateway import interp2app, unwrap_spec
6 from pypy.interpreter.typedef import (TypeDef, GetSetProperty,
7 interp_attrproperty, interp_attrproperty_w)
8 from rpython.annotator.model import SomeChar
9 from rpython.rlib import jit
10 from rpython.rlib.objectmodel import (
11 specialize, we_are_translated, enforceargs, dict_to_switch)
12 from rpython.rlib.rarithmetic import r_longlong, r_ulonglong, ovfcheck
13 from pypy.module.micronumpy import types, boxes, support, constants as NPY
14 from .base import W_NDimArray
15 from pypy.module.micronumpy.appbridge import get_appbridge_cache
16 from pypy.module.micronumpy.converters import byteorder_converter
17 from pypy.module.micronumpy.hashdescr import _array_descr_walk
18
19
20 def decode_w_dtype(space, w_dtype):
21 if space.is_none(w_dtype):
22 return None
23 if isinstance(w_dtype, W_Dtype):
24 return w_dtype
25 return space.interp_w(
26 W_Dtype, space.call_function(space.gettypefor(W_Dtype), w_dtype))
27
28 @jit.unroll_safe
29 def dtype_agreement(space, w_arr_list, shape, out=None):
30 """ agree on dtype from a list of arrays. if out is allocated,
31 use it's dtype, otherwise allocate a new one with agreed dtype
32 """
33 from .casting import find_result_type
34
35 if not space.is_none(out):
36 return out
37 arr_w = [w_arr for w_arr in w_arr_list if not space.is_none(w_arr)]
38 dtype = find_result_type(space, arr_w, [])
39 assert dtype is not None
40 out = W_NDimArray.from_shape(space, shape, dtype)
41 return out
42
43 def byteorder_w(space, w_str):
44 order = space.text_w(w_str)
45 if len(order) != 1:
46 raise oefmt(space.w_ValueError,
47 "endian is not 1-char string in Numpy dtype unpickling")
48 endian = order[0]
49 if endian not in (NPY.LITTLE, NPY.BIG, NPY.NATIVE, NPY.IGNORE):
50 raise oefmt(space.w_ValueError, "Invalid byteorder %s", endian)
51 return endian
52
53
54
55 class W_Dtype(W_Root):
56 _immutable_fields_ = [
57 "itemtype?", "w_box_type", "byteorder?", "names?", "fields?",
58 "elsize?", "alignment?", "shape?", "subdtype?", "base?", "flags?"]
59
60 @enforceargs(byteorder=SomeChar())
61 def __init__(self, itemtype, w_box_type, byteorder=NPY.NATIVE, names=[],
62 fields={}, elsize=-1, shape=[], subdtype=None):
63 self.itemtype = itemtype
64 self.w_box_type = w_box_type
65 if itemtype.get_element_size() == 1 or isinstance(itemtype, types.ObjectType):
66 byteorder = NPY.IGNORE
67 self.byteorder = byteorder
68 self.names = names
69 self.fields = fields
70 if elsize < 0:
71 elsize = itemtype.get_element_size()
72 self.elsize = elsize
73 self.shape = shape
74 self.subdtype = subdtype
75 self.flags = 0
76 self.metadata = None
77 if isinstance(itemtype, types.ObjectType):
78 self.flags = NPY.OBJECT_DTYPE_FLAGS
79 if not subdtype:
80 self.base = self
81 self.alignment = itemtype.get_element_size()
82 else:
83 self.base = subdtype.base
84 self.alignment = subdtype.itemtype.get_element_size()
85
86 @property
87 def num(self):
88 return self.itemtype.num
89
90 @property
91 def kind(self):
92 return self.itemtype.kind
93
94 @property
95 def char(self):
96 return self.itemtype.char
97
98 def __repr__(self):
99 if self.fields:
100 return '<DType %r>' % self.fields
101 return '<DType %r>' % self.itemtype
102
103 @specialize.argtype(1)
104 def box(self, value):
105 if self.is_record():
106 raise oefmt(self.itemtype.space.w_NotImplementedError,
107 "cannot box a value into a 'record' dtype, this is a bug please report it")
108 return self.itemtype.box(value)
109
110 @specialize.argtype(1, 2)
111 def box_complex(self, real, imag):
112 return self.itemtype.box_complex(real, imag)
113
114 def coerce(self, space, w_item):
115 return self.itemtype.coerce(space, self, w_item)
116
117 def is_bool(self):
118 return self.kind == NPY.GENBOOLLTR
119
120 def is_signed(self):
121 return self.kind == NPY.SIGNEDLTR
122
123 def is_unsigned(self):
124 return self.kind == NPY.UNSIGNEDLTR
125
126 def is_int(self):
127 return (self.kind == NPY.SIGNEDLTR or self.kind == NPY.UNSIGNEDLTR or
128 self.kind == NPY.GENBOOLLTR)
129
130 def is_float(self):
131 return self.kind == NPY.FLOATINGLTR
132
133 def is_complex(self):
134 return self.kind == NPY.COMPLEXLTR
135
136 def is_number(self):
137 return self.is_int() or self.is_float() or self.is_complex()
138
139 def is_str(self):
140 return self.num == NPY.STRING
141
142 def is_unicode(self):
143 return self.num == NPY.UNICODE
144
145 def is_object(self):
146 return self.num == NPY.OBJECT
147
148 def is_str_or_unicode(self):
149 return self.num == NPY.STRING or self.num == NPY.UNICODE
150
151 def is_flexible(self):
152 return self.is_str_or_unicode() or self.num == NPY.VOID
153
154 def is_record(self):
155 return bool(self.fields)
156
157 def is_native(self):
158 # Use ord() to ensure that self.byteorder is a char and JITs properly
159 return ord(self.byteorder) in (ord(NPY.NATIVE), ord(NPY.NATBYTE))
160
161 def as_signed(self, space):
162 """Convert from an unsigned integer dtype to its signed partner"""
163 if self.is_unsigned():
164 return num2dtype(space, self.num - 1)
165 else:
166 return self
167
168 def as_unsigned(self, space):
169 """Convert from a signed integer dtype to its unsigned partner"""
170 if self.is_signed():
171 return num2dtype(space, self.num + 1)
172 else:
173 return self
174
175 def get_float_dtype(self, space):
176 assert self.is_complex()
177 dtype = get_dtype_cache(space).component_dtypes(self.num)
178 if self.byteorder == NPY.OPPBYTE:
179 dtype = dtype.descr_newbyteorder(space)
180 assert dtype.is_float()
181 return dtype
182
183 def getformat(self, stringbuilder):
184 # adapted from _buffer_format_string in multiarray/buffer.c
185 # byte-order not supported yet
186 if self.is_record():
187 #subs = sorted(self.fields.items(), key=lambda (k,v): v[0])
188 subs = []
189 for name in self.fields:
190 offset, dtyp = self.fields[name]
191 i = 0
192 for i in range(len(subs)):
193 if offset < subs[i][0]:
194 break
195 else:
196 i = len(subs)
197 subs.insert(i, (offset, dtyp, name))
198 start = 0
199 stringbuilder.append('T{')
200 for s in subs:
201 stringbuilder.append('x' * (s[0] - start))
202 start = s[0] + s[1].elsize
203 s[1].getformat(stringbuilder)
204 stringbuilder.append(':')
205 stringbuilder.append(s[2])
206 stringbuilder.append(':')
207 stringbuilder.append('}')
208 else:
209 if self.byteorder == NPY.OPPBYTE:
210 raise oefmt(self.itemtype.space.w_NotImplementedError,
211 "non-native byte order not supported yet")
212 # even if not, NumPy adds a '=', '@', for 'i' types
213 stringbuilder.append(self.char)
214
215 def get_name(self):
216 name = self.w_box_type.getname(self.itemtype.space)
217 if name.endswith('_'):
218 name = name[:-1]
219 return name
220
221 def descr_get_name(self, space, quote=False):
222 if quote:
223 name = "'" + self.get_name() + "'"
224 else:
225 name = self.get_name()
226 if self.is_flexible() and self.elsize != 0:
227 return space.newtext(name + str(self.elsize * 8))
228 return space.newtext(name)
229
230 def descr_get_str(self, space, ignore='|', simple=True):
231 if not simple and self.fields and len(self.fields) > 0:
232 return self.descr_get_descr(space)
233 total = 0
234 for s in self.shape:
235 total += s
236 if not simple and total > 0:
237 return space.newtuple(
238 [space.newtext(self.subdtype.get_str(ignore='')),
239 space.newtuple([space.newint(s) for s in self.shape]),
240 ])
241 return space.newtext(self.get_str(ignore=ignore))
242
243 def get_str(self, ignore='|'):
244 basic = self.kind
245 endian = self.byteorder
246 size = self.elsize
247 if endian == NPY.NATIVE:
248 endian = NPY.NATBYTE
249 elif endian == NPY.IGNORE:
250 endian = ignore
251 if self.num == NPY.UNICODE:
252 size >>= 2
253 if self.num == NPY.OBJECT:
254 return "%s%s" %(endian, basic)
255 return "%s%s%s" % (endian, basic, size)
256
257 def descr_get_descr(self, space, style='descr', force_dict=False):
258 simple = False
259 if style == 'descr':
260 simple = True
261 if not self.is_record():
262 return space.newlist([space.newtuple([space.newtext(""),
263 self.descr_get_str(space, simple=simple)])])
264 elif (self.alignment > 1 and not style.startswith('descr')) or force_dict:
265 # we need to force a sorting order for the keys,
266 # so return a string instead of a dict. Also, numpy formats
267 # the lists without spaces between elements, so we cannot simply
268 # do str(names)
269 names = ["'names':["]
270 formats = ["'formats':["]
271 offsets = ["'offsets':["]
272 titles = ["'titles':["]
273 use_titles = False
274 show_offsets = False
275 offsets_n = []
276 total = 0
277 for name, title in self.names:
278 offset, subdtype = self.fields[name]
279 if subdtype.is_record():
280 substr = [space.text_w(space.str(subdtype.descr_get_descr(
281 space, style='descr_subdtype'))), ","]
282 elif subdtype.subdtype is not None:
283 substr = ["(", space.text_w(space.str(
284 subdtype.subdtype.descr_get_descr(space, style='descr_subdtype'))),
285 ', ',
286 space.text_w(space.repr(space.newtuple([space.newint(s) for s in subdtype.shape]))),
287 "),"]
288 else:
289 substr = ["'", subdtype.get_str(ignore=''), "',"]
290 formats += substr
291 offsets += [str(offset), ',']
292 names += ["'", name, "',"]
293 titles += ["'", str(title), "',"]
294 if title is not None:
295 use_titles = True
296 if total != offset:
297 show_offsets = True
298 total += subdtype.elsize
299 # make sure offsets_n is sorted
300 i = 0
301 for i in range(len(offsets_n)):
302 if offset < offsets_n[i]:
303 break
304 offsets_n.insert(i, offset)
305 total = 0
306 for i in range(len(offsets_n)):
307 if offsets_n[i] != self.alignment * i:
308 show_offsets = True
309 if use_titles and not show_offsets:
310 return self.descr_get_descr(space, style='descr')
311 # replace the last , with a ]
312 formats[-1] = formats[-1][:-1] + ']'
313 offsets[-1] = offsets[-1][:-1] + ']'
314 names[-1] = names[-1][:-1] + ']'
315 titles[-1] = titles[-1][:-1] + ']'
316 if self.alignment < 2 or style.endswith('subdtype'):
317 suffix = "}"
318 elif style == 'str':
319 suffix = ", 'aligned':True}"
320 elif style == 'substr':
321 suffix = '}'
322 else:
323 suffix = "}, align=True"
324 s_as_list = ['{'] + names + [', '] + formats + [', '] + offsets + [', ']
325 if use_titles:
326 s_as_list += titles + [', ']
327
328 s_as_list += ["'itemsize':", str(self.elsize), suffix]
329 return space.newtext(''.join(s_as_list))
330 else:
331 descr = []
332 total = 0
333 for name, title in self.names:
334 offset, subdtype = self.fields[name]
335 show_offsets = False
336 if total != offset and len(subdtype.shape) < 1:
337 # whoops, need to use other format
338 return self.descr_get_descr(space, style=style + '_subdtype', force_dict=True)
339 total += subdtype.elsize
340 ignore = '|'
341 if title:
342 subdescr = [space.newtuple([space.newtext(title), space.newtext(name)])]
343 ignore = ''
344 else:
345 subdescr = [space.newtext(name)]
346 if subdtype.is_record():
347 subdescr.append(subdtype.descr_get_descr(space, style))
348 elif subdtype.subdtype is not None:
349 subdescr.append(subdtype.subdtype.descr_get_str(space, simple=False))
350 else:
351 subdescr.append(subdtype.descr_get_str(space, ignore=ignore, simple=False))
352 if subdtype.shape != []:
353 subdescr.append(subdtype.descr_get_shape(space))
354 descr.append(space.newtuple(subdescr[:]))
355 if self.alignment >= 0 and not style.endswith('subdtype'):
356 return space.newtext(space.text_w(space.repr(space.newlist(descr))) + ', align=True')
357 return space.newlist(descr)
358
359 def descr_get_hasobject(self, space):
360 return space.newbool(self.is_object())
361
362 def descr_get_isbuiltin(self, space):
363 if self.fields is None:
364 return space.newint(1)
365 return space.newint(0)
366
367 def descr_get_isnative(self, space):
368 return space.newbool(self.is_native())
369
370 def descr_get_base(self, space):
371 return self.base
372
373 def descr_get_subdtype(self, space):
374 if self.subdtype is None:
375 return space.w_None
376 return space.newtuple([self.subdtype,
377 self.descr_get_shape(space)])
378
379 def descr_get_shape(self, space):
380 return space.newtuple([space.newint(dim) for dim in self.shape])
381
382 def descr_get_flags(self, space):
383 return space.newint(self.flags)
384
385 def descr_get_fields(self, space):
386 if not self.fields:
387 return space.w_None
388 w_fields = space.newdict()
389 for name, title in self.names:
390 offset, subdtype = self.fields[name]
391 if title is not None:
392 w_nt = space.newtuple([space.newtext(name), space.newtext(title)])
393 space.setitem(w_fields, w_nt,
394 space.newtuple([subdtype, space.newint(offset)]))
395 else:
396 space.setitem(w_fields, space.newtext(name),
397 space.newtuple([subdtype, space.newint(offset)]))
398 return w_fields
399
400 def descr_get_names(self, space):
401 if not self.fields:
402 return space.w_None
403 return space.newtuple([space.newtext(name[0]) for name in self.names])
404
405 def descr_set_names(self, space, w_names):
406 if not self.fields:
407 raise oefmt(space.w_ValueError, "there are no fields defined")
408 if not space.issequence_w(w_names) or \
409 space.len_w(w_names) != len(self.names):
410 raise oefmt(space.w_ValueError,
411 "must replace all names at once "
412 "with a sequence of length %d",
413 len(self.names))
414 names = []
415 names_w = space.fixedview(w_names)
416 for i in range(len(names_w)):
417 w_name = names_w[i]
418 title = self.names[i][1]
419 if not space.isinstance_w(w_name, space.w_text):
420 raise oefmt(space.w_ValueError,
421 "item #%d of names is of type %T and not string",
422 len(names), w_name)
423 names.append((space.text_w(w_name), title))
424 fields = {}
425 for i in range(len(self.names)):
426 if names[i][0] in fields:
427 raise oefmt(space.w_ValueError, "Duplicate field names given.")
428 fields[names[i][0]] = self.fields[self.names[i][0]]
429 if self.names[i][1] is not None:
430 fields[self.names[i][1]] = self.fields[self.names[i][0]]
431 self.fields = fields
432 self.names = names
433
434 def descr_del_names(self, space):
435 raise oefmt(space.w_AttributeError,
436 "Cannot delete dtype names attribute")
437
438 def descr_get_metadata(self, space):
439 if self.metadata is None:
440 return space.w_None
441 return self.metadata
442
443 def descr_set_metadata(self, space, w_metadata):
444 if w_metadata is None:
445 return
446 if not space.isinstance_w(w_metadata, space.w_dict):
447 raise oefmt(space.w_TypeError, "argument 4 must be dict, not str")
448 self.metadata = w_metadata
449
450 def descr_del_metadata(self, space):
451 self.metadata = None
452
453 def eq(self, space, w_other):
454 w_other = space.call_function(space.gettypefor(W_Dtype), w_other)
455 if space.is_w(self, w_other):
456 return True
457 if isinstance(w_other, W_Dtype):
458 if self.is_object() and w_other.is_object():
459 # ignore possible 'record' unions
460 # created from dtype(('O', spec))
461 return True
462 return space.eq_w(self.descr_reduce(space),
463 w_other.descr_reduce(space))
464 return False
465
466 def descr_eq(self, space, w_other):
467 return space.newbool(self.eq(space, w_other))
468
469 def descr_ne(self, space, w_other):
470 return space.newbool(not self.eq(space, w_other))
471
472 def descr_le(self, space, w_other):
473 from .casting import can_cast_to
474 w_other = as_dtype(space, w_other)
475 return space.newbool(can_cast_to(self, w_other))
476
477 def descr_ge(self, space, w_other):
478 from .casting import can_cast_to
479 w_other = as_dtype(space, w_other)
480 return space.newbool(can_cast_to(w_other, self))
481
482 def descr_lt(self, space, w_other):
483 from .casting import can_cast_to
484 w_other = as_dtype(space, w_other)
485 return space.newbool(can_cast_to(self, w_other) and not self.eq(space, w_other))
486
487 def descr_gt(self, space, w_other):
488 from .casting import can_cast_to
489 w_other = as_dtype(space, w_other)
490 return space.newbool(can_cast_to(w_other, self) and not self.eq(space, w_other))
491
492 def descr_hash(self, space):
493 tl = _array_descr_walk(space, self)
494 return space.hash(space.newtuple(tl[:]))
495
496 def descr_str(self, space):
497 if self.fields:
498 r = self.descr_get_descr(space, style='str')
499 name = space.text_w(space.str(self.w_box_type))
500 if name != "<type 'numpy.void'>":
501 boxname = space.str(self.w_box_type)
502 r = space.newtuple([self.w_box_type, r])
503 return space.str(r)
504 elif self.subdtype is not None:
505 return space.str(space.newtuple([
506 self.subdtype.descr_get_str(space),
507 self.descr_get_shape(space)]))
508 else:
509 if self.is_flexible():
510 return self.descr_get_str(space)
511 else:
512 return self.descr_get_name(space)
513
514 def descr_repr(self, space):
515 if isinstance(self.itemtype, types.CharType):
516 return space.newtext("dtype('S1')")
517 if self.fields:
518 r = self.descr_get_descr(space, style='repr')
519 name = space.text_w(space.str(self.w_box_type))
520 if name != "<type 'numpy.void'>":
521 r = space.newtuple([self.w_box_type, r])
522 elif self.subdtype is not None:
523 r = space.newtuple([self.subdtype.descr_get_str(space),
524 self.descr_get_shape(space)])
525 else:
526 if self.is_flexible():
527 if self.byteorder != NPY.IGNORE:
528 byteorder = NPY.NATBYTE if self.is_native() else NPY.OPPBYTE
529 else:
530 byteorder = ''
531 size = self.elsize
532 if self.num == NPY.UNICODE:
533 size >>= 2
534 r = space.newtext("'" + byteorder + self.char + str(size) + "'")
535 else:
536 r = self.descr_get_name(space, quote=True)
537 if space.isinstance_w(r, space.w_text):
538 return space.newtext("dtype(%s)" % space.text_w(r))
539 return space.newtext("dtype(%s)" % space.text_w(space.repr(r)))
540
541 def descr_getitem(self, space, w_item):
542 if not self.fields:
543 raise oefmt(space.w_KeyError, "There are no fields in dtype %s.",
544 self.get_name())
545 if space.isinstance_w(w_item, space.w_text):
546 item = space.text_w(w_item)
547 elif space.isinstance_w(w_item, space.w_bytes):
548 item = space.bytes_w(w_item) # XXX should it be supported?
549 elif space.isinstance_w(w_item, space.w_int):
550 indx = space.int_w(w_item)
551 try:
552 item,title = self.names[indx]
553 except IndexError:
554 raise oefmt(space.w_IndexError,
555 "Field index %d out of range.", indx)
556 else:
557 raise oefmt(space.w_ValueError,
558 "Field key must be an integer, string, or unicode.")
559 try:
560 return self.fields[item][1]
561 except KeyError:
562 raise oefmt(space.w_KeyError,
563 "Field named '%s' not found.", item)
564
565 def descr_len(self, space):
566 if not self.fields:
567 return space.newint(0)
568 return space.newint(len(self.fields))
569
570 def runpack_str(self, space, s):
571 if self.is_str_or_unicode():
572 return self.coerce(space, space.newbytes(s))
573 return self.itemtype.runpack_str(space, s, self.is_native())
574
575 def store(self, arr, i, offset, value):
576 return self.itemtype.store(arr, i, offset, value, self.is_native())
577
578 def read(self, arr, i, offset):
579 return self.itemtype.read(arr, i, offset, self)
580
581 def read_bool(self, arr, i, offset):
582 return self.itemtype.read_bool(arr, i, offset, self)
583
584 def descr_reduce(self, space):
585 w_class = space.type(self)
586 builder_args = space.newtuple([
587 space.newbytes("%s%d" % (self.kind, self.elsize)),
588 space.newint(0), space.newint(1)])
589
590 version = space.newint(3)
591 endian = self.byteorder
592 if endian == NPY.NATIVE:
593 endian = NPY.NATBYTE
594 subdescr = self.descr_get_subdtype(space)
595 names = self.descr_get_names(space)
596 values = self.descr_get_fields(space)
597 if self.is_flexible():
598 w_size = space.newint(self.elsize)
599 if self.alignment > 2:
600 w_alignment = space.newint(self.alignment)
601 else:
602 w_alignment = space.newint(1)
603 else:
604 w_size = space.newint(-1)
605 w_alignment = space.newint(-1)
606 w_flags = space.newint(self.flags)
607
608 data = space.newtuple([version, space.newbytes(endian), subdescr,
609 names, values, w_size, w_alignment, w_flags])
610 return space.newtuple([w_class, builder_args, data])
611
612 def descr_setstate(self, space, w_data):
613 if self.fields is None and not isinstance(self.itemtype, types.VoidType):
614 # if builtin dtype (but not w_voiddtype)
615 return space.w_None
616
617 version = space.int_w(space.getitem(w_data, space.newint(0)))
618 if version != 3:
619 raise oefmt(space.w_ValueError,
620 "can't handle version %d of numpy.dtype pickle",
621 version)
622
623 endian = byteorder_w(space, space.getitem(w_data, space.newint(1)))
624 if endian == NPY.NATBYTE:
625 endian = NPY.NATIVE
626
627 w_subarray = space.getitem(w_data, space.newint(2))
628 w_names = space.getitem(w_data, space.newint(3))
629 w_fields = space.getitem(w_data, space.newint(4))
630 size = space.int_w(space.getitem(w_data, space.newint(5)))
631 alignment = space.int_w(space.getitem(w_data, space.newint(6)))
632 if alignment < 2:
633 alignment = -1
634 flags = space.int_w(space.getitem(w_data, space.newint(7)))
635
636 if (w_names == space.w_None) != (w_fields == space.w_None):
637 raise oefmt(space.w_ValueError, "inconsistent fields and names in Numpy dtype unpickling")
638
639 self.byteorder = endian
640 self.shape = []
641 self.subdtype = None
642 self.base = self
643
644 if w_subarray != space.w_None:
645 if not space.isinstance_w(w_subarray, space.w_tuple) or \
646 space.len_w(w_subarray) != 2:
647 raise oefmt(space.w_ValueError,
648 "incorrect subarray in __setstate__")
649 subdtype, w_shape = space.fixedview(w_subarray)
650 assert isinstance(subdtype, W_Dtype)
651 if not support.issequence_w(space, w_shape):
652 self.shape = [space.int_w(w_shape)]
653 else:
654 self.shape = [space.int_w(w_s) for w_s in space.fixedview(w_shape)]
655 self.subdtype = subdtype
656 self.base = subdtype.base
657
658 if w_names != space.w_None:
659 self.names = []
660 self.fields = {}
661 for w_name in space.fixedview(w_names):
662 # XXX what happens if there is a title in the pickled dtype?
663 name = space.bytes_w(w_name)
664 value = space.getitem(w_fields, w_name)
665
666 dtype = space.getitem(value, space.newint(0))
667 offset = space.int_w(space.getitem(value, space.newint(1)))
668 self.names.append((name, None))
669 assert isinstance(dtype, W_Dtype)
670 self.fields[name] = offset, dtype
671 self.itemtype = types.RecordType(space)
672
673 if self.is_flexible():
674 self.elsize = size
675 self.alignment = alignment
676 self.flags = flags
677
678 @unwrap_spec(new_order='text')
679 def descr_newbyteorder(self, space, new_order=NPY.SWAP):
680 newendian = byteorder_converter(space, new_order)
681 endian = self.byteorder
682 if endian != NPY.IGNORE:
683 if newendian == NPY.SWAP:
684 endian = NPY.OPPBYTE if self.is_native() else NPY.NATBYTE
685 elif newendian != NPY.IGNORE:
686 endian = newendian
687 fields = self.fields
688 if fields is None:
689 fields = {}
690 return W_Dtype(self.itemtype,
691 self.w_box_type, byteorder=endian, elsize=self.elsize,
692 names=self.names, fields=fields,
693 shape=self.shape, subdtype=self.subdtype)
694
695
696 @specialize.arg(2)
697 def dtype_from_list(space, w_lst, simple, alignment, offsets=None, itemsize=0):
698 lst_w = space.listview(w_lst)
699 fields = {}
700 use_supplied_offsets = True
701 if offsets is None:
702 use_supplied_offsets = False
703 offsets = [0] * len(lst_w)
704 maxalign = alignment
705 fldnames = [''] * len(lst_w)
706 subdtypes = [None] * len(lst_w)
707 titles = [None] * len(lst_w)
708 total = 0
709 for i in range(len(lst_w)):
710 w_elem = lst_w[i]
711 if simple:
712 subdtype = make_new_dtype(space, space.gettypefor(W_Dtype), w_elem,
713 maxalign)
714 fldnames[i] = 'f%d' % i
715 else:
716 w_shape = space.newtuple([])
717 if space.len_w(w_elem) == 3:
718 w_fldname, w_flddesc, w_shape = space.fixedview(w_elem)
719 if not support.issequence_w(space, w_shape):
720 w_shape = space.newtuple([w_shape])
721 else:
722 w_fldname, w_flddesc = space.fixedview(w_elem, 2)
723 subdtype = make_new_dtype(space, space.gettypefor(W_Dtype),
724 w_flddesc, maxalign, w_shape=w_shape)
725 if space.isinstance_w(w_fldname, space.w_tuple):
726 fldlist = space.listview(w_fldname)
727 fldnames[i] = space.text_w(fldlist[0])
728 if space.is_w(fldlist[1], space.w_None):
729 titles[i] = None
730 else:
731 titles[i] = space.text_w(fldlist[1])
732 if len(fldlist) != 2:
733 raise oefmt(space.w_TypeError, "data type not understood")
734 elif space.isinstance_w(w_fldname, space.w_text):
735 fldnames[i] = space.text_w(w_fldname)
736 else:
737 raise oefmt(space.w_TypeError, "data type not understood")
738 if fldnames[i] == '':
739 fldnames[i] = 'f%d' % i
740 assert isinstance(subdtype, W_Dtype)
741 if alignment >= 0:
742 maxalign = max(subdtype.alignment, maxalign)
743 delta = subdtype.alignment
744 # Set offset to the next power-of-two above delta
745 delta = (delta + maxalign -1) & (-maxalign)
746 if not use_supplied_offsets:
747 if delta > offsets[i]:
748 for j in range(i):
749 offsets[j+1] = delta + offsets[j]
750 if i + 1 < len(offsets) and offsets[i + 1] == 0:
751 offsets[i + 1] = offsets[i] + max(delta, subdtype.elsize)
752 # sanity check
753 if offsets[i] % maxalign:
754 offsets[i] = ((offsets[i] // maxalign) + 1) * maxalign
755 elif not use_supplied_offsets:
756 if i + 1 < len(offsets) and offsets[i + 1] == 0:
757 offsets[i+1] = offsets[i] + subdtype.elsize
758 subdtypes[i] = subdtype
759 if use_supplied_offsets:
760 sz = subdtype.elsize
761 else:
762 sz = max(maxalign, subdtype.elsize)
763 if offsets[i] + sz > total:
764 total = offsets[i] + sz
765 # padding?
766 if alignment >= 0 and total % maxalign:
767 total = total // maxalign * maxalign + maxalign
768 names = []
769 for i in range(len(subdtypes)):
770 subdtype = subdtypes[i]
771 assert isinstance(subdtype, W_Dtype)
772 if alignment >=0 and subdtype.is_record():
773 subdtype.alignment = maxalign
774 if fldnames[i] in fields:
775 raise oefmt(space.w_ValueError, "two fields with the same name")
776 if maxalign > 1 and offsets[i] % subdtype.alignment:
777 raise oefmt(space.w_ValueError, "offset %d for NumPy dtype with "
778 "fields is not divisible by the field alignment %d "
779 "with align=True", offsets[i], maxalign)
780 fields[fldnames[i]] = offsets[i], subdtype
781 if titles[i] is not None:
782 if titles[i] in fields:
783 raise oefmt(space.w_ValueError, "two fields with the same name")
784 fields[titles[i]] = offsets[i], subdtype
785 names.append((fldnames[i], titles[i]))
786 if itemsize > 1:
787 if total > itemsize:
788 raise oefmt(space.w_ValueError,
789 "NumPy dtype descriptor requires %d bytes, cannot"
790 " override to smaller itemsize of %d", total, itemsize)
791 if alignment >= 0 and itemsize % maxalign:
792 raise oefmt(space.w_ValueError,
793 "NumPy dtype descriptor requires alignment of %d bytes, "
794 "which is not divisible into the specified itemsize %d",
795 maxalign, itemsize)
796 total = itemsize
797 retval = W_Dtype(types.RecordType(space), space.gettypefor(boxes.W_VoidBox),
798 names=names, fields=fields, elsize=total)
799 if alignment >=0:
800 retval.alignment = maxalign
801 else:
802 retval.alignment = -1
803 retval.flags |= NPY.NEEDS_PYAPI
804 return retval
805
806 def _get_val_or_none(space, w_dict, key):
807 w_key = space.newtext(key)
808 try:
809 w_val = space.getitem(w_dict, w_key)
810 except OperationError as e:
811 if e.match(space, space.w_KeyError):
812 return None
813 else:
814 raise
815 return w_val
816
817 def _get_list_or_none(space, w_dict, key):
818 w_val = _get_val_or_none(space, w_dict, key)
819 if w_val is None:
820 return None
821 if space.isinstance_w(w_val, space.w_set):
822 raise oefmt(space.w_TypeError, "'set' object does not support indexing")
823 return space.listview(w_val)
824
825 def _usefields(space, w_dict, align):
826 # Only for testing, a shortened version of the real _usefields
827 allfields = []
828 for fname_w in space.unpackiterable(w_dict):
829 obj = _get_list_or_none(space, w_dict, space.text_w(fname_w))
830 num = space.int_w(obj[1])
831 if align:
832 alignment = 0
833 else:
834 alignment = -1
835 format = dtype_from_spec(space, obj[0], alignment=alignment)
836 if len(obj) > 2:
837 title = obj[2]
838 else:
839 title = space.w_None
840 allfields.append((fname_w, format, num, title))
841 #allfields.sort(key=lambda x: x[2])
842 names = [space.newtuple([x[0], x[3]]) for x in allfields]
843 formats = [x[1] for x in allfields]
844 offsets = [x[2] for x in allfields]
845 aslist = []
846 if align:
847 alignment = 0
848 else:
849 alignment = -1
850 for i in range(len(names)):
851 aslist.append(space.newtuple([names[i], formats[i]]))
852 return dtype_from_list(space, space.newlist(aslist), False, alignment, offsets=offsets)
853
854 def dtype_from_dict(space, w_dict, alignment):
855 from pypy.objspace.std.dictmultiobject import W_DictMultiObject
856 assert isinstance(w_dict, W_DictMultiObject)
857 names_w = _get_list_or_none(space, w_dict, 'names')
858 formats_w = _get_list_or_none(space, w_dict, 'formats')
859 offsets_w = _get_list_or_none(space, w_dict, 'offsets')
860 titles_w = _get_list_or_none(space, w_dict, 'titles')
861 metadata_w = _get_val_or_none(space, w_dict, 'metadata')
862 aligned_w = _get_val_or_none(space, w_dict, 'aligned')
863 itemsize_w = _get_val_or_none(space, w_dict, 'itemsize')
864 if names_w is None or formats_w is None:
865 try:
866 return get_appbridge_cache(space).call_method(space,
867 'numpy.core._internal', '_usefields', Arguments(space,
868 [w_dict, space.newbool(alignment >= 0)]))
869 except OperationError as e:
870 if e.match(space, space.w_ImportError):
871 return _usefields(space, w_dict, alignment >= 0)
872 raise
873 n = len(names_w)
874 if (n != len(formats_w) or
875 (offsets_w is not None and n != len(offsets_w)) or
876 (titles_w is not None and n != len(titles_w))):
877 raise oefmt(space.w_ValueError, "'names', 'formats', 'offsets', and "
878 "'titles' dicct entries must have the same length")
879 if aligned_w is not None:
880 if space.isinstance_w(aligned_w, space.w_bool) and space.is_true(aligned_w):
881 if alignment < 0:
882 alignment = 0
883 else:
884 raise oefmt(space.w_ValueError,
885 "NumPy dtype descriptor includes 'aligned' entry, "
886 "but its value is neither True nor False");
887 if offsets_w is None:
888 offsets = None
889 else:
890 offsets = [space.int_w(i) for i in offsets_w]
891 if titles_w is not None:
892 _names_w = []
893 for i in range(min(len(names_w), len(titles_w))):
894 _names_w.append(space.newtuple([names_w[i], titles_w[i]]))
895 names_w = _names_w
896 aslist = []
897 if itemsize_w is None:
898 itemsize = 0
899 else:
900 itemsize = space.int_w(itemsize_w)
901 for i in range(min(len(names_w), len(formats_w))):
902 aslist.append(space.newtuple([names_w[i], formats_w[i]]))
903 retval = dtype_from_list(space, space.newlist(aslist), False, alignment,
904 offsets=offsets, itemsize=itemsize)
905 if metadata_w is not None:
906 retval.descr_set_metadata(space, metadata_w)
907 retval.flags |= NPY.NEEDS_PYAPI
908 return retval
909
910 def dtype_from_spec(space, w_spec, alignment):
911
912 w_lst = w_spec
913 try:
914 w_lst = get_appbridge_cache(space).call_method(space,
915 'numpy.core._internal', '_commastring', Arguments(space, [w_spec]))
916 except OperationError as e:
917 if not e.match(space, space.w_ImportError):
918 raise
919 # handle only simple cases for testing
920 if space.isinstance_w(w_spec, space.w_text):
921 spec = [s.strip() for s in space.text_w(w_spec).split(',')]
922 w_lst = space.newlist([space.newtext(s) for s in spec])
923 if not space.isinstance_w(w_lst, space.w_list) or space.len_w(w_lst) < 1:
924 raise oefmt(space.w_RuntimeError,
925 "_commastring is not returning a list with len >= 1")
926 if space.len_w(w_lst) == 1:
927 return descr__new__(space, space.gettypefor(W_Dtype),
928 space.getitem(w_lst, space.newint(0)), align=alignment>0)
929 else:
930 try:
931 return dtype_from_list(space, w_lst, True, alignment)
932 except OperationError as e:
933 if e.match(space, space.w_TypeError):
934 return dtype_from_list(space, w_lst, False, alignment)
935 raise
936
937 def _check_for_commastring(s):
938 if s[0] in string.digits or s[0] in '<>=|' and s[1] in string.digits:
939 return True
940 if s[0] == '(' and s[1] == ')' or s[0] in '<>=|' and s[1] == '(' and s[2] == ')':
941 return True
942 sqbracket = 0
943 for c in s:
944 if c == ',':
945 if sqbracket == 0:
946 return True
947 elif c == '[':
948 sqbracket += 1
949 elif c == ']':
950 sqbracket -= 1
951 return False
952
953 def _set_metadata_and_copy(space, w_metadata, dtype, copy=False):
954 cache = get_dtype_cache(space)
955 assert isinstance(dtype, W_Dtype)
956 if copy or (dtype in cache.builtin_dtypes and w_metadata is not None):
957 dtype = W_Dtype(dtype.itemtype, dtype.w_box_type, dtype.byteorder)
958 if w_metadata is not None:
959 dtype.descr_set_metadata(space, w_metadata)
960 return dtype
961
962 def _get_shape(space, w_shape):
963 if w_shape is None:
964 return None
965 if space.isinstance_w(w_shape, space.w_int):
966 dim = space.int_w(w_shape)
967 if dim == 1:
968 return None
969 return [dim]
970 shape_w = space.fixedview(w_shape)
971 if len(shape_w) < 1:
972 return None
973 elif space.isinstance_w(shape_w[0], space.w_tuple):
974 # (base_dtype, new_dtype) dtype spectification
975 return None
976 shape = []
977 for w_dim in shape_w:
978 try:
979 dim = space.int_w(w_dim)
980 except OperationError as e:
981 if e.match(space, space.w_OverflowError):
982 raise oefmt(space.w_ValueError, "invalid shape in fixed-type tuple.")
983 else:
984 raise
985 if dim > 0x7fffffff:
986 raise oefmt(space.w_ValueError, "invalid shape in fixed-type tuple: "
987 "dimension does not fit into a C int.")
988 elif dim < 0:
989 raise oefmt(space.w_ValueError, "invalid shape in fixed-type tuple: "
990 "dimension smaller than zero.")
991 shape.append(dim)
992 return shape
993
994 @unwrap_spec(align=bool, copy=bool)
995 def descr__new__(space, w_subtype, w_dtype, align=False, copy=False,
996 w_shape=None, w_metadata=None):
997 if align:
998 alignment = 0
999 else:
1000 alignment = -1
1001 return make_new_dtype(space, w_subtype, w_dtype, alignment, copy=copy,
1002 w_shape=w_shape, w_metadata=w_metadata)
1003
1004 def make_new_dtype(space, w_subtype, w_dtype, alignment, copy=False, w_shape=None, w_metadata=None):
1005 cache = get_dtype_cache(space)
1006 shape = _get_shape(space, w_shape)
1007 if shape is not None:
1008 subdtype = make_new_dtype(space, w_subtype, w_dtype, alignment, copy, w_metadata=w_metadata)
1009 assert isinstance(subdtype, W_Dtype)
1010 try:
1011 size = support.product(shape)
1012 size = ovfcheck(size * subdtype.elsize)
1013 except OverflowError:
1014 raise oefmt(space.w_ValueError, "invalid shape in fixed-type tuple: "
1015 "dtype size in bytes must fit into a C int.")
1016 if size > 0x7fffffff:
1017 raise oefmt(space.w_ValueError, "invalid shape in fixed-type tuple: "
1018 "dtype size in bytes must fit into a C int.")
1019
1020 return _set_metadata_and_copy(space, w_metadata,
1021 W_Dtype(types.VoidType(space), space.gettypefor(boxes.W_VoidBox),
1022 shape=shape, subdtype=subdtype, elsize=size))
1023 elif w_shape is not None and not space.isinstance_w(w_shape, space.w_int):
1024 spec = space.listview(w_shape)
1025 if len(spec) > 0:
1026 # this is (base_dtype, new_dtype) so just make it a union by setting both
1027 # parts' offset to 0
1028 w_dtype1 = make_new_dtype(space, w_subtype, w_shape, alignment)
1029 assert isinstance(w_dtype, W_Dtype)
1030 assert isinstance(w_dtype1, W_Dtype)
1031 if (w_dtype.elsize != 0 and w_dtype1.elsize != 0 and
1032 w_dtype1.elsize != w_dtype.elsize):
1033 raise oefmt(space.w_ValueError,
1034 'mismatch in size of old and new data-descriptor')
1035 retval = W_Dtype(w_dtype.itemtype, w_dtype.w_box_type,
1036 names=w_dtype1.names[:], fields=w_dtype1.fields.copy(),
1037 elsize=w_dtype1.elsize)
1038 return retval
1039 if space.is_none(w_dtype):
1040 return cache.w_float64dtype
1041 if space.isinstance_w(w_dtype, w_subtype):
1042 return w_dtype
1043 if space.isinstance_w(w_dtype, space.w_unicode):
1044 name = space.text_w(w_dtype)
1045 if _check_for_commastring(name):
1046 return _set_metadata_and_copy(space, w_metadata,
1047 dtype_from_spec(space, w_dtype, alignment))
1048 cname = name[1:] if name[0] == NPY.OPPBYTE else name
1049 try:
1050 dtype = cache.dtypes_by_name[cname]
1051 except KeyError:
1052 pass
1053 else:
1054 if name[0] == NPY.OPPBYTE:
1055 dtype = dtype.descr_newbyteorder(space)
1056 return dtype
1057 if name[0] in 'VSUca' or name[0] in '<>=|' and name[1] in 'VSUca':
1058 return variable_dtype(space, name)
1059 raise oefmt(space.w_TypeError, 'data type "%s" not understood', name)
1060 elif space.isinstance_w(w_dtype, space.w_list):
1061 return _set_metadata_and_copy( space, w_metadata,
1062 dtype_from_list(space, w_dtype, False, alignment), copy)
1063 elif space.isinstance_w(w_dtype, space.w_tuple):
1064 w_dtype0 = space.getitem(w_dtype, space.newint(0))
1065 w_dtype1 = space.getitem(w_dtype, space.newint(1))
1066 # create a new dtype object
1067 l_side = make_new_dtype(space, w_subtype, w_dtype0, alignment, copy)
1068 assert isinstance(l_side, W_Dtype)
1069 if l_side.elsize == 0 and space.isinstance_w(w_dtype1, space.w_int):
1070 #(flexible_dtype, itemsize)
1071 name = "%s%d" % (l_side.kind, space.int_w(w_dtype1))
1072 retval = make_new_dtype(space, w_subtype, space.newtext(name), alignment, copy)
1073 return _set_metadata_and_copy(space, w_metadata, retval, copy)
1074 elif (space.isinstance_w(w_dtype1, space.w_int) or
1075 space.isinstance_w(w_dtype1, space.w_tuple) or
1076 space.isinstance_w(w_dtype1, space.w_list) or
1077 isinstance(w_dtype1, W_NDimArray)):
1078 #(fixed_dtype, shape) or (base_dtype, new_dtype)
1079 retval = make_new_dtype(space, w_subtype, l_side, alignment,
1080 copy, w_shape=w_dtype1)
1081 return _set_metadata_and_copy(space, w_metadata, retval, copy)
1082 elif space.isinstance_w(w_dtype, space.w_dict):
1083 return _set_metadata_and_copy(space, w_metadata,
1084 dtype_from_dict(space, w_dtype, alignment), copy)
1085 for dtype in cache.builtin_dtypes:
1086 try:
1087 constructors = cache.alternate_constructors(dtype.num)
1088 except KeyError:
1089 pass
1090 else:
1091 if w_dtype in constructors:
1092 return _set_metadata_and_copy(space, w_metadata, dtype, copy)
1093 if w_dtype is dtype.w_box_type:
1094 return _set_metadata_and_copy(space, w_metadata, dtype, copy)
1095 if space.isinstance_w(w_dtype, space.w_type) and \
1096 space.issubtype_w(w_dtype, dtype.w_box_type):
1097 return _set_metadata_and_copy( space, w_metadata,
1098 W_Dtype(dtype.itemtype, w_dtype, elsize=0), copy)
1099 if space.isinstance_w(w_dtype, space.w_type):
1100 return _set_metadata_and_copy(space, w_metadata, cache.w_objectdtype, copy)
1101 raise oefmt(space.w_TypeError, "data type not understood")
1102
1103
1104 W_Dtype.typedef = TypeDef("numpy.dtype",
1105 __new__ = interp2app(descr__new__),
1106
1107 type = interp_attrproperty_w("w_box_type", cls=W_Dtype),
1108 kind = interp_attrproperty("kind", cls=W_Dtype, wrapfn="newtext"),
1109 char = interp_attrproperty("char", cls=W_Dtype, wrapfn="newtext"),
1110 num = interp_attrproperty("num", cls=W_Dtype, wrapfn="newint"),
1111 byteorder = interp_attrproperty("byteorder", cls=W_Dtype, wrapfn="newtext"),
1112 itemsize = interp_attrproperty("elsize", cls=W_Dtype, wrapfn="newint"),
1113 alignment = interp_attrproperty("alignment", cls=W_Dtype, wrapfn="newint"),
1114
1115 name = GetSetProperty(W_Dtype.descr_get_name),
1116 str = GetSetProperty(W_Dtype.descr_get_str),
1117 descr = GetSetProperty(W_Dtype.descr_get_descr),
1118 hasobject = GetSetProperty(W_Dtype.descr_get_hasobject),
1119 isbuiltin = GetSetProperty(W_Dtype.descr_get_isbuiltin),
1120 isnative = GetSetProperty(W_Dtype.descr_get_isnative),
1121 base = GetSetProperty(W_Dtype.descr_get_base),
1122 subdtype = GetSetProperty(W_Dtype.descr_get_subdtype),
1123 shape = GetSetProperty(W_Dtype.descr_get_shape),
1124 fields = GetSetProperty(W_Dtype.descr_get_fields),
1125 names = GetSetProperty(W_Dtype.descr_get_names,
1126 W_Dtype.descr_set_names,
1127 W_Dtype.descr_del_names),
1128 metadata = GetSetProperty(W_Dtype.descr_get_metadata,
1129 #W_Dtype.descr_set_metadata,
1130 #W_Dtype.descr_del_metadata,
1131 ),
1132 flags = GetSetProperty(W_Dtype.descr_get_flags),
1133
1134 __eq__ = interp2app(W_Dtype.descr_eq),
1135 __ne__ = interp2app(W_Dtype.descr_ne),
1136 __lt__ = interp2app(W_Dtype.descr_lt),
1137 __le__ = interp2app(W_Dtype.descr_le),
1138 __gt__ = interp2app(W_Dtype.descr_gt),
1139 __ge__ = interp2app(W_Dtype.descr_ge),
1140 __hash__ = interp2app(W_Dtype.descr_hash),
1141 __str__= interp2app(W_Dtype.descr_str),
1142 __repr__ = interp2app(W_Dtype.descr_repr),
1143 __getitem__ = interp2app(W_Dtype.descr_getitem),
1144 __len__ = interp2app(W_Dtype.descr_len),
1145 __reduce__ = interp2app(W_Dtype.descr_reduce),
1146 __setstate__ = interp2app(W_Dtype.descr_setstate),
1147 newbyteorder = interp2app(W_Dtype.descr_newbyteorder),
1148 )
1149 W_Dtype.typedef.acceptable_as_base_class = False
1150
1151
1152 def variable_dtype(space, name):
1153 if name[0] in '<>=|':
1154 name = name[1:]
1155 char = name[0]
1156 if len(name) == 1:
1157 size = 0
1158 else:
1159 try:
1160 size = int(name[1:])
1161 except ValueError:
1162 raise oefmt(space.w_TypeError, "data type not understood")
1163 if char == NPY.CHARLTR and size == 0:
1164 return W_Dtype(
1165 types.CharType(space),
1166 elsize=1,
1167 w_box_type=space.gettypefor(boxes.W_StringBox))
1168 elif char == NPY.STRINGLTR or char == NPY.STRINGLTR2:
1169 return new_string_dtype(space, size)
1170 elif char == NPY.UNICODELTR:
1171 return new_unicode_dtype(space, size)
1172 elif char == NPY.VOIDLTR:
1173 return new_void_dtype(space, size)
1174 raise oefmt(space.w_TypeError, 'data type "%s" not understood', name)
1175
1176
1177 def new_string_dtype(space, size):
1178 return W_Dtype(
1179 types.StringType(space),
1180 elsize=size,
1181 w_box_type=space.gettypefor(boxes.W_StringBox),
1182 )
1183
1184
1185 def new_unicode_dtype(space, size):
1186 itemtype = types.UnicodeType(space)
1187 return W_Dtype(
1188 itemtype,
1189 elsize=size * itemtype.get_element_size(),
1190 w_box_type=space.gettypefor(boxes.W_UnicodeBox),
1191 )
1192
1193
1194 def new_void_dtype(space, size):
1195 return W_Dtype(
1196 types.VoidType(space),
1197 elsize=size,
1198 w_box_type=space.gettypefor(boxes.W_VoidBox),
1199 )
1200
1201
1202 class DtypeCache(object):
1203 def __init__(self, space):
1204 self.w_booldtype = W_Dtype(
1205 types.Bool(space),
1206 w_box_type=space.gettypefor(boxes.W_BoolBox),
1207 )
1208 self.w_int8dtype = W_Dtype(
1209 types.Int8(space),
1210 w_box_type=space.gettypefor(boxes.W_Int8Box),
1211 )
1212 self.w_uint8dtype = W_Dtype(
1213 types.UInt8(space),
1214 w_box_type=space.gettypefor(boxes.W_UInt8Box),
1215 )
1216 self.w_int16dtype = W_Dtype(
1217 types.Int16(space),
1218 w_box_type=space.gettypefor(boxes.W_Int16Box),
1219 )
1220 self.w_uint16dtype = W_Dtype(
1221 types.UInt16(space),
1222 w_box_type=space.gettypefor(boxes.W_UInt16Box),
1223 )
1224 self.w_int32dtype = W_Dtype(
1225 types.Int32(space),
1226 w_box_type=space.gettypefor(boxes.W_Int32Box),
1227 )
1228 self.w_uint32dtype = W_Dtype(
1229 types.UInt32(space),
1230 w_box_type=space.gettypefor(boxes.W_UInt32Box),
1231 )
1232 self.w_longdtype = W_Dtype(
1233 types.Long(space),
1234 w_box_type=space.gettypefor(boxes.W_LongBox),
1235 )
1236 self.w_ulongdtype = W_Dtype(
1237 types.ULong(space),
1238 w_box_type=space.gettypefor(boxes.W_ULongBox),
1239 )
1240 self.w_int64dtype = W_Dtype(
1241 types.Int64(space),
1242 w_box_type=space.gettypefor(boxes.W_Int64Box),
1243 )
1244 self.w_uint64dtype = W_Dtype(
1245 types.UInt64(space),
1246 w_box_type=space.gettypefor(boxes.W_UInt64Box),
1247 )
1248 self.w_float32dtype = W_Dtype(
1249 types.Float32(space),
1250 w_box_type=space.gettypefor(boxes.W_Float32Box),
1251 )
1252 self.w_float64dtype = W_Dtype(
1253 types.Float64(space),
1254 w_box_type=space.gettypefor(boxes.W_Float64Box),
1255 )
1256 self.w_floatlongdtype = W_Dtype(
1257 types.FloatLong(space),
1258 w_box_type=space.gettypefor(boxes.W_FloatLongBox),
1259 )
1260 self.w_complex64dtype = W_Dtype(
1261 types.Complex64(space),
1262 w_box_type=space.gettypefor(boxes.W_Complex64Box),
1263 )
1264 self.w_complex128dtype = W_Dtype(
1265 types.Complex128(space),
1266 w_box_type=space.gettypefor(boxes.W_Complex128Box),
1267 )
1268 self.w_complexlongdtype = W_Dtype(
1269 types.ComplexLong(space),
1270 w_box_type=space.gettypefor(boxes.W_ComplexLongBox),
1271 )
1272 self.w_stringdtype = W_Dtype(
1273 types.StringType(space),
1274 elsize=0,
1275 w_box_type=space.gettypefor(boxes.W_StringBox),
1276 )
1277 self.w_unicodedtype = W_Dtype(
1278 types.UnicodeType(space),
1279 elsize=0,
1280 w_box_type=space.gettypefor(boxes.W_UnicodeBox),
1281 )
1282 self.w_voiddtype = W_Dtype(
1283 types.VoidType(space),
1284 elsize=0,
1285 w_box_type=space.gettypefor(boxes.W_VoidBox),
1286 )
1287 self.w_float16dtype = W_Dtype(
1288 types.Float16(space),
1289 w_box_type=space.gettypefor(boxes.W_Float16Box),
1290 )
1291 self.w_objectdtype = W_Dtype(
1292 types.ObjectType(space),
1293 w_box_type=space.gettypefor(boxes.W_ObjectBox),
1294 )
1295 aliases = {
1296 NPY.BOOL: ['bool_', 'bool8'],
1297 NPY.BYTE: ['byte'],
1298 NPY.UBYTE: ['ubyte'],
1299 NPY.SHORT: ['short'],
1300 NPY.USHORT: ['ushort'],
1301 NPY.LONG: ['int'],
1302 NPY.ULONG: ['uint'],
1303 NPY.LONGLONG: ['longlong'],
1304 NPY.ULONGLONG: ['ulonglong'],
1305 NPY.FLOAT: ['single'],
1306 NPY.DOUBLE: ['float', 'double'],
1307 NPY.LONGDOUBLE: ['longdouble', 'longfloat'],
1308 NPY.CFLOAT: ['csingle'],
1309 NPY.CDOUBLE: ['complex', 'cfloat', 'cdouble'],
1310 NPY.CLONGDOUBLE: ['clongdouble', 'clongfloat'],
1311 NPY.STRING: ['string_', 'str'],
1312 NPY.UNICODE: ['unicode_'],
1313 NPY.OBJECT: ['object_'],
1314 }
1315 self.alternate_constructors = dict_to_switch({
1316 NPY.BOOL: [space.w_bool],
1317 NPY.LONG: [space.w_int,
1318 space.gettypefor(boxes.W_IntegerBox),
1319 space.gettypefor(boxes.W_SignedIntegerBox)],
1320 NPY.ULONG: [space.gettypefor(boxes.W_UnsignedIntegerBox)],
1321 NPY.LONGLONG: [space.w_int],
1322 NPY.DOUBLE: [space.w_float,
1323 space.gettypefor(boxes.W_NumberBox),
1324 space.gettypefor(boxes.W_FloatingBox)],
1325 NPY.CDOUBLE: [space.w_complex,
1326 space.gettypefor(boxes.W_ComplexFloatingBox)],
1327 NPY.STRING: [space.w_bytes,
1328 space.gettypefor(boxes.W_CharacterBox)],
1329 NPY.UNICODE: [space.w_unicode],
1330 NPY.VOID: [space.gettypefor(boxes.W_GenericBox)],
1331 #space.w_buffer, # XXX no buffer in space
1332 NPY.OBJECT: [space.gettypefor(boxes.W_ObjectBox),
1333 space.w_object],
1334 })
1335 float_dtypes = [self.w_float16dtype, self.w_float32dtype,
1336 self.w_float64dtype, self.w_floatlongdtype]
1337 complex_dtypes = [self.w_complex64dtype, self.w_complex128dtype,
1338 self.w_complexlongdtype]
1339 self.component_dtypes = dict_to_switch({
1340 NPY.CFLOAT: self.w_float32dtype,
1341 NPY.CDOUBLE: self.w_float64dtype,
1342 NPY.CLONGDOUBLE: self.w_floatlongdtype,
1343 })
1344 integer_dtypes = [
1345 self.w_int8dtype, self.w_uint8dtype,
1346 self.w_int16dtype, self.w_uint16dtype,
1347 self.w_int32dtype, self.w_uint32dtype,
1348 self.w_longdtype, self.w_ulongdtype,
1349 self.w_int64dtype, self.w_uint64dtype]
1350 self.builtin_dtypes = ([self.w_booldtype] + integer_dtypes +
1351 float_dtypes + complex_dtypes + [
1352 self.w_stringdtype, self.w_unicodedtype, self.w_voiddtype,
1353 self.w_objectdtype,
1354 ])
1355 self.integer_dtypes = integer_dtypes
1356 self.float_dtypes = float_dtypes
1357 self.complex_dtypes = complex_dtypes
1358 self.float_dtypes_by_num_bytes = sorted(
1359 (dtype.elsize, dtype)
1360 for dtype in float_dtypes
1361 )
1362 dtypes_by_num = {}
1363 self.dtypes_by_name = {}
1364 # we reverse, so the stuff with lower numbers override stuff with
1365 # higher numbers
1366 # However, Long/ULong always take precedence over Intxx
1367 for dtype in reversed(
1368 [self.w_longdtype, self.w_ulongdtype] + self.builtin_dtypes):
1369 dtype.fields = None # mark these as builtin
1370 dtypes_by_num[dtype.num] = dtype
1371 self.dtypes_by_name[dtype.get_name()] = dtype
1372 for can_name in [dtype.kind + str(dtype.elsize),
1373 dtype.char]:
1374 self.dtypes_by_name[can_name] = dtype
1375 self.dtypes_by_name[NPY.NATBYTE + can_name] = dtype
1376 self.dtypes_by_name[NPY.NATIVE + can_name] = dtype
1377 self.dtypes_by_name[NPY.IGNORE + can_name] = dtype
1378 if dtype.num in aliases:
1379 for alias in aliases[dtype.num]:
1380 self.dtypes_by_name[alias] = dtype
1381 self.dtypes_by_num = dict_to_switch(dtypes_by_num)
1382 if self.w_longdtype.elsize == self.w_int32dtype.elsize:
1383 intp_dtype = self.w_int32dtype
1384 uintp_dtype = self.w_uint32dtype
1385 else:
1386 intp_dtype = self.w_longdtype
1387 uintp_dtype = self.w_ulongdtype
1388 self.dtypes_by_name['p'] = self.dtypes_by_name['intp'] = intp_dtype
1389 self.dtypes_by_name['P'] = self.dtypes_by_name['uintp'] = uintp_dtype
1390
1391 typeinfo_full = {
1392 'LONGLONG': self.w_int64dtype,
1393 'SHORT': self.w_int16dtype,
1394 'VOID': self.w_voiddtype,
1395 'UBYTE': self.w_uint8dtype,
1396 'UINTP': self.w_ulongdtype,
1397 'ULONG': self.w_ulongdtype,
1398 'LONG': self.w_longdtype,
1399 'UNICODE': self.w_unicodedtype,
1400 #'OBJECT',
1401 'ULONGLONG': self.w_uint64dtype,
1402 'STRING': self.w_stringdtype,
1403 'CFLOAT': self.w_complex64dtype,
1404 'CDOUBLE': self.w_complex128dtype,
1405 'CLONGDOUBLE': self.w_complexlongdtype,
1406 #'DATETIME',
1407 'UINT': self.w_uint32dtype,
1408 'INTP': self.w_longdtype,
1409 'HALF': self.w_float16dtype,
1410 'BYTE': self.w_int8dtype,
1411 #'TIMEDELTA',
1412 'INT': self.w_int32dtype,
1413 'DOUBLE': self.w_float64dtype,
1414 'LONGDOUBLE': self.w_floatlongdtype,
1415 'USHORT': self.w_uint16dtype,
1416 'FLOAT': self.w_float32dtype,
1417 'BOOL': self.w_booldtype,
1418 'OBJECT': self.w_objectdtype,
1419 }
1420
1421 typeinfo_partial = {
1422 'Generic': boxes.W_GenericBox,
1423 'Character': boxes.W_CharacterBox,
1424 'Flexible': boxes.W_FlexibleBox,
1425 'Inexact': boxes.W_InexactBox,
1426 'Integer': boxes.W_IntegerBox,
1427 'SignedInteger': boxes.W_SignedIntegerBox,
1428 'UnsignedInteger': boxes.W_UnsignedIntegerBox,
1429 'ComplexFloating': boxes.W_ComplexFloatingBox,
1430 'Number': boxes.W_NumberBox,
1431 'Floating': boxes.W_FloatingBox
1432 }
1433 w_typeinfo = space.newdict()
1434 for k, v in typeinfo_partial.iteritems():
1435 space.setitem(w_typeinfo, space.newtext(k), space.gettypefor(v))
1436 for k, dtype in typeinfo_full.iteritems():
1437 itembits = dtype.elsize * 8
1438 if k in ('INTP', 'UINTP'):
1439 char = getattr(NPY, k + 'LTR')
1440 else:
1441 char = dtype.char
1442 items_w = [space.newtext(char),
1443 space.newint(dtype.num),
1444 space.newint(itembits),
1445 space.newint(dtype.itemtype.get_element_size())]
1446 if dtype.is_int():
1447 if dtype.is_bool():
1448 w_maxobj = space.newint(1)
1449 w_minobj = space.newint(0)
1450 elif dtype.is_signed():
1451 w_maxobj = space.newint(r_longlong((1 << (itembits - 1))
1452 - 1))
1453 w_minobj = space.newint(r_longlong(-1) << (itembits - 1))
1454 else:
1455 w_maxobj = space.newint(r_ulonglong(1 << itembits) - 1)
1456 w_minobj = space.newint(0)
1457 items_w = items_w + [w_maxobj, w_minobj]
1458 items_w = items_w + [dtype.w_box_type]
1459 space.setitem(w_typeinfo, space.newtext(k), space.newtuple(items_w))
1460 self.w_typeinfo = w_typeinfo
1461
1462
1463 def get_dtype_cache(space):
1464 return space.fromcache(DtypeCache)
1465
1466 @jit.elidable
1467 def num2dtype(space, num):
1468 return get_dtype_cache(space).dtypes_by_num(num)
1469
1470 def as_dtype(space, w_arg, allow_None=True):
1471 from pypy.module.micronumpy.casting import scalar2dtype
1472 # roughly equivalent to CNumPy's PyArray_DescrConverter2
1473 if not allow_None and space.is_none(w_arg):
1474 raise TypeError("Cannot create dtype from None here")
1475 if isinstance(w_arg, W_NDimArray):
1476 return w_arg.get_dtype()
1477 elif is_scalar_w(space, w_arg):
1478 result = scalar2dtype(space, w_arg)
1479 return result
1480 else:
1481 return space.interp_w(W_Dtype,
1482 space.call_function(space.gettypefor(W_Dtype), w_arg))
1483
1484 def is_scalar_w(space, w_arg):
1485 return (isinstance(w_arg, boxes.W_GenericBox) or
1486 space.isinstance_w(w_arg, space.w_int) or
1487 space.isinstance_w(w_arg, space.w_float) or
1488 space.isinstance_w(w_arg, space.w_complex) or
1489 space.isinstance_w(w_arg, space.w_bool))