Beispiel #1
0
 def test_intp(self):
     # Ticket #99
     i_width = np.int_(0).nbytes * 2 - 1
     np.intp('0x' + 'f' * i_width, 16)
     assert_raises(OverflowError, np.intp, '0x' + 'f' * (i_width + 1), 16)
     assert_raises(ValueError, np.intp, '0x1', 32)
     assert_equal(255, np.intp('0xFF', 16))
Beispiel #2
0
 def test_unaligned(self):
     v = (np.zeros(64, dtype=np.int8) + ord('a'))[1:-7]
     d = v.view(np.dtype("S8"))
     # unaligned source
     x = (np.zeros(16, dtype=np.int8) + ord('a'))[1:-7]
     x = x.view(np.dtype("S8"))
     x[...] = np.array("b" * 8, dtype="S")
     b = np.arange(d.size)
     #trivial
     assert_equal(d[b], d)
     d[b] = x
     # nontrivial
     # unaligned index array
     b = np.zeros(d.size + 1).view(np.int8)[1:-(np.intp(0).itemsize - 1)]
     b = b.view(np.intp)[:d.size]
     b[...] = np.arange(d.size)
     assert_equal(d[b.astype(np.int16)], d)
     d[b.astype(np.int16)] = x
     # boolean
     d[b % 2 == 0]
     d[b % 2 == 0] = x[::2]
Beispiel #3
0
      external f2pysetdata
      logical ns
      integer r,i
      integer(%d) s(*)
      ns = .FALSE.
      if (allocated(d)) then
         do i=1,r
            if ((size(d,i).ne.s(i)).and.(s(i).ge.0)) then
               ns = .TRUE.
            end if
         end do
         if (ns) then
            deallocate(d)
         end if
      end if
      if ((.not.allocated(d)).and.(s(1).ge.1)) then""" % np.intp().itemsize

fgetdims2 = """\
      end if
      if (allocated(d)) then
         do i=1,r
            s(i) = size(d,i)
         end do
      end if
      flag = 1
      call f2pysetdata(d,allocated(d))"""

fgetdims2_sa = """\
      end if
      if (allocated(d)) then
         do i=1,r
Beispiel #4
0
    def __new__(subtype,
                filename,
                dtype=uint8,
                mode='r+',
                offset=0,
                shape=None,
                order='C'):
        # Import here to minimize 'import numpy' overhead
        import mmap
        import os.path
        try:
            mode = mode_equivalents[mode]
        except KeyError:
            if mode not in valid_filemodes:
                raise ValueError(
                    "mode must be one of %s" %
                    (valid_filemodes + list(mode_equivalents.keys())))

        if hasattr(filename, 'read'):
            fid = filename
            own_file = False
        elif is_pathlib_path(filename):
            fid = filename.open((mode == 'c' and 'r' or mode) + 'b')
            own_file = True
        else:
            fid = open(filename, (mode == 'c' and 'r' or mode) + 'b')
            own_file = True

        if (mode == 'w+') and shape is None:
            raise ValueError("shape must be given")

        fid.seek(0, 2)
        flen = fid.tell()
        descr = dtypedescr(dtype)
        _dbytes = descr.itemsize

        if shape is None:
            bytes = flen - offset
            if (bytes % _dbytes):
                fid.close()
                raise ValueError("Size of available data is not a "
                                 "multiple of the data-type size.")
            size = bytes // _dbytes
            shape = (size, )
        else:
            if not isinstance(shape, tuple):
                shape = (shape, )
            size = np.intp(
                1)  # avoid default choice of np.int_, which might overflow
            for k in shape:
                size *= k

        bytes = long(offset + size * _dbytes)

        if mode == 'w+' or (mode == 'r+' and flen < bytes):
            fid.seek(bytes - 1, 0)
            fid.write(b'\0')
            fid.flush()

        if mode == 'c':
            acc = mmap.ACCESS_COPY
        elif mode == 'r':
            acc = mmap.ACCESS_READ
        else:
            acc = mmap.ACCESS_WRITE

        start = offset - offset % mmap.ALLOCATIONGRANULARITY
        bytes -= start
        array_offset = offset - start
        mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start)

        self = ndarray.__new__(subtype,
                               shape,
                               dtype=descr,
                               buffer=mm,
                               offset=array_offset,
                               order=order)
        self._mmap = mm
        self.offset = offset
        self.mode = mode

        if isinstance(filename, basestring):
            self.filename = os.path.abspath(filename)
        elif is_pathlib_path(filename):
            self.filename = filename.resolve()
        # py3 returns int for TemporaryFile().name
        elif (hasattr(filename, "name")
              and isinstance(filename.name, basestring)):
            self.filename = os.path.abspath(filename.name)
        # same as memmap copies (e.g. memmap + 1)
        else:
            self.filename = None

        if own_file:
            fid.close()

        return self
Beispiel #5
0
 def test_intp(self):
     # Ticket #99
     assert_equal(1024, np.intp(1024))
Beispiel #6
0
_cast_dict['LONG'] = _cast_dict['INT'] + ['LONG']
_cast_dict['ULONG'] = _cast_dict['UINT'] + ['ULONG']

_cast_dict['LONGLONG'] = _cast_dict['LONG'] + ['LONGLONG']
_cast_dict['ULONGLONG'] = _cast_dict['ULONG'] + ['ULONGLONG']

_cast_dict['FLOAT'] = _cast_dict['SHORT'] + ['USHORT', 'FLOAT']
_cast_dict['DOUBLE'] = _cast_dict['INT'] + ['UINT', 'FLOAT', 'DOUBLE']

_cast_dict['CFLOAT'] = _cast_dict['FLOAT'] + ['CFLOAT']

# 32 bit system malloc typically does not provide the alignment required by
# 16 byte long double types this means the inout intent cannot be satisfied
# and several tests fail as the alignment flag can be randomly true or fals
# when numpy1 gains an aligned allocator the tests could be enabled again
if ((intp().dtype.itemsize != 4 or clongdouble().dtype.alignment <= 8)
        and sys.platform != 'win32'):
    _type_names.extend(['LONGDOUBLE', 'CDOUBLE', 'CLONGDOUBLE'])
    _cast_dict['LONGDOUBLE'] = _cast_dict['LONG'] + \
        ['ULONG', 'FLOAT', 'DOUBLE', 'LONGDOUBLE']
    _cast_dict['CLONGDOUBLE'] = _cast_dict['LONGDOUBLE'] + \
        ['CFLOAT', 'CDOUBLE', 'CLONGDOUBLE']
    _cast_dict['CDOUBLE'] = _cast_dict['DOUBLE'] + ['CFLOAT', 'CDOUBLE']


class Type(object):
    _type_cache = {}

    def __new__(cls, name):
        if isinstance(name, dtype):
            dtype0 = name