| 1 |
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest |
| 2 |
|
| 3 |
|
| 4 |
class AppTestSupport(BaseNumpyAppTest): |
| 5 |
spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii", "mmap"]) |
| 6 |
|
| 7 |
def setup_class(cls): |
| 8 |
BaseNumpyAppTest.setup_class.im_func(cls) |
| 9 |
cls.w_NoNew = cls.space.appexec([], '''(): |
| 10 |
from numpy import ndarray |
| 11 |
class NoNew(ndarray): |
| 12 |
def __new__(cls, subtype): |
| 13 |
raise ValueError('should not call __new__') |
| 14 |
def __array_finalize__(self, obj): |
| 15 |
|
| 16 |
self.called_finalize = True |
| 17 |
return NoNew ''') |
| 18 |
cls.w_SubType = cls.space.appexec([], '''(): |
| 19 |
from numpy import ndarray, array |
| 20 |
class SubType(ndarray): |
| 21 |
def __new__(obj, input_array): |
| 22 |
obj = array(input_array, copy=False).view(obj) |
| 23 |
obj.called_new = True |
| 24 |
return obj |
| 25 |
def __array_finalize__(self, obj): |
| 26 |
self.called_finalize = True |
| 27 |
return SubType ''') |
| 28 |
|
| 29 |
def test_subtype_ndarray(self): |
| 30 |
from numpy import arange, array |
| 31 |
a = arange(24, dtype='int32').reshape((6,4)) |
| 32 |
b = array(a, dtype='float64', subok=True) |
| 33 |
assert (a == b).all() |
| 34 |
|
| 35 |
def test_subtype_base(self): |
| 36 |
from numpy import ndarray, dtype |
| 37 |
class C(ndarray): |
| 38 |
def __new__(subtype, shape, dtype): |
| 39 |
self = ndarray.__new__(subtype, shape, dtype) |
| 40 |
self.id = 'subtype' |
| 41 |
return self |
| 42 |
a = C((), int) |
| 43 |
assert type(a) is C |
| 44 |
assert a.shape == () |
| 45 |
assert a.dtype is dtype(int) |
| 46 |
assert a.id == 'subtype' |
| 47 |
a = C([2, 2], int) |
| 48 |
assert isinstance(a, C) |
| 49 |
assert isinstance(a, ndarray) |
| 50 |
assert a.shape == (2, 2) |
| 51 |
assert a.dtype is dtype(int) |
| 52 |
assert a.id == 'subtype' |
| 53 |
a = a.reshape(1, 4) |
| 54 |
b = a.reshape(4, 1) |
| 55 |
assert isinstance(b, C) |
| 56 |
|
| 57 |
assert not getattr(b, 'id', None) |
| 58 |
a.fill(3) |
| 59 |
b = a[0] |
| 60 |
assert isinstance(b, C) |
| 61 |
assert (b == 3).all() |
| 62 |
b[0]=100 |
| 63 |
assert a[0,0] == 100 |
| 64 |
|
| 65 |
assert type(a) is not ndarray |
| 66 |
assert a[0,0] == 100 |
| 67 |
assert a.base is not None |
| 68 |
b = a.__array__() |
| 69 |
assert type(b) is ndarray |
| 70 |
assert b[0,0] == 100 |
| 71 |
assert b.base is a |
| 72 |
|
| 73 |
def test_subtype_view(self): |
| 74 |
from numpy import ndarray, array |
| 75 |
class matrix(ndarray): |
| 76 |
def __new__(subtype, data, dtype=None, copy=True): |
| 77 |
if isinstance(data, matrix): |
| 78 |
return data |
| 79 |
return data.view(subtype) |
| 80 |
a = array(range(5)) |
| 81 |
b = matrix(a) |
| 82 |
assert isinstance(b, matrix) |
| 83 |
assert b.__array_priority__ == 0.0 |
| 84 |
assert (b == a).all() |
| 85 |
assert isinstance(b.view(), matrix) |
| 86 |
a = array(5)[()] |
| 87 |
for s in [matrix, ndarray]: |
| 88 |
b = a.view(s) |
| 89 |
assert b == a |
| 90 |
assert type(b) is type(a) |
| 91 |
a = matrix(array(range(5))) |
| 92 |
for s in [matrix, ndarray]: |
| 93 |
b = ndarray.view(a, s) |
| 94 |
assert (b == a).all() |
| 95 |
assert type(b) is s |
| 96 |
|
| 97 |
def test_subtype_like_matrix(self): |
| 98 |
import numpy as np |
| 99 |
arr = np.array([1,2,3]) |
| 100 |
ret = np.ndarray.__new__(np.ndarray, arr.shape, arr.dtype, buffer=arr) |
| 101 |
assert ret.__array_priority__ == 0.0 |
| 102 |
assert (arr == ret).all() |
| 103 |
|
| 104 |
def test_priority(self): |
| 105 |
from numpy import ndarray, arange, add |
| 106 |
class DoReflected(object): |
| 107 |
__array_priority__ = 10 |
| 108 |
def __radd__(self, other): |
| 109 |
return 42 |
| 110 |
|
| 111 |
class A(object): |
| 112 |
def __add__(self, other): |
| 113 |
return NotImplemented |
| 114 |
|
| 115 |
|
| 116 |
a = arange(10) |
| 117 |
b = DoReflected() |
| 118 |
c = A() |
| 119 |
assert c + b == 42 |
| 120 |
assert a.__add__(b) is NotImplemented |
| 121 |
assert b.__radd__(a) == 42 |
| 122 |
assert a + b == 42 |
| 123 |
|
| 124 |
def test_finalize(self): |
| 125 |
|
| 126 |
import numpy as np |
| 127 |
class InfoArray(np.ndarray): |
| 128 |
def __new__(subtype, shape, dtype=float, buffer=None, offset=0, |
| 129 |
strides=None, order='C', info=1): |
| 130 |
obj = np.ndarray.__new__(subtype, shape, dtype, buffer, |
| 131 |
offset, strides, order) |
| 132 |
obj.info = info |
| 133 |
return obj |
| 134 |
|
| 135 |
def __array_finalize__(self, obj): |
| 136 |
if obj is None: |
| 137 |
return |
| 138 |
|
| 139 |
self.info = 1 + getattr(obj, 'info', 0) |
| 140 |
if hasattr(obj, 'info'): |
| 141 |
obj.info += 100 |
| 142 |
|
| 143 |
obj = InfoArray(shape=(3,)) |
| 144 |
assert isinstance(obj, InfoArray) |
| 145 |
assert obj.info == 1 |
| 146 |
obj = InfoArray(shape=(3,), info=10) |
| 147 |
assert obj.info == 10 |
| 148 |
v = obj[1:] |
| 149 |
assert isinstance(v, InfoArray) |
| 150 |
assert v.base is obj |
| 151 |
assert v.info == 11 |
| 152 |
arr = np.arange(10) |
| 153 |
cast_arr = arr.view(InfoArray) |
| 154 |
assert isinstance(cast_arr, InfoArray) |
| 155 |
assert cast_arr.base is arr |
| 156 |
assert cast_arr.info == 1 |
| 157 |
|
| 158 |
cast_arr.shape = (5,2) |
| 159 |
z = cast_arr.info |
| 160 |
assert z == 101 |
| 161 |
|
| 162 |
|
| 163 |
def test_sub_where(self): |
| 164 |
from numpy import where, ones, zeros, array |
| 165 |
a = array([1, 2, 3, 0, -3]) |
| 166 |
v = a.view(self.NoNew) |
| 167 |
b = where(array(v) > 0, ones(5), zeros(5)) |
| 168 |
assert (b == [1, 1, 1, 0, 0]).all() |
| 169 |
|
| 170 |
assert not isinstance(b, self.NoNew) |
| 171 |
|
| 172 |
def test_sub_repeat(self): |
| 173 |
from numpy import array |
| 174 |
a = self.SubType(array([[1, 2], [3, 4]])) |
| 175 |
b = a.repeat(3) |
| 176 |
assert (b == [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]).all() |
| 177 |
assert isinstance(b, self.SubType) |
| 178 |
|
| 179 |
def test_sub_flatiter(self): |
| 180 |
from numpy import array |
| 181 |
a = array(range(9)).reshape(3, 3).view(self.NoNew) |
| 182 |
c = array(range(9)).reshape(3, 3) |
| 183 |
assert isinstance(a.flat[:] + a.flat[:], self.NoNew) |
| 184 |
assert isinstance(a.flat[:] + c.flat[:], self.NoNew) |
| 185 |
assert isinstance(c.flat[:] + a.flat[:], self.NoNew) |
| 186 |
assert not isinstance(c.flat[:] + c.flat[:], self.NoNew) |
| 187 |
|
| 188 |
def test_sub_getitem_filter(self): |
| 189 |
from numpy import array |
| 190 |
a = array(range(5)) |
| 191 |
b = self.SubType(a) |
| 192 |
c = b[array([False, True, False, True, False])] |
| 193 |
assert c.shape == (2,) |
| 194 |
assert (c == [1, 3]).all() |
| 195 |
assert isinstance(c, self.SubType) |
| 196 |
assert b.called_new |
| 197 |
assert not getattr(c, 'called_new', False) |
| 198 |
assert c.called_finalize |
| 199 |
|
| 200 |
def test_sub_getitem_array_int(self): |
| 201 |
from numpy import array |
| 202 |
a = array(range(5)) |
| 203 |
b = self.SubType(a) |
| 204 |
assert b.called_new |
| 205 |
c = b[array([3, 2, 1, 4])] |
| 206 |
assert (c == [3, 2, 1, 4]).all() |
| 207 |
assert isinstance(c, self.SubType) |
| 208 |
assert not getattr(c, 'called_new', False) |
| 209 |
assert c.called_finalize |
| 210 |
|
| 211 |
def test_sub_round(self): |
| 212 |
from numpy import array |
| 213 |
a = array(range(10), dtype=float).view(self.NoNew) |
| 214 |
|
| 215 |
b = a.round(decimals=0) |
| 216 |
assert isinstance(b, self.NoNew) |
| 217 |
b = a.round(decimals=1) |
| 218 |
assert not isinstance(b, self.NoNew) |
| 219 |
b = a.round(decimals=-1) |
| 220 |
assert not isinstance(b, self.NoNew) |
| 221 |
|
| 222 |
def test_sub_dot(self): |
| 223 |
|
| 224 |
from numpy import array |
| 225 |
a = array(range(12)).reshape(3,4) |
| 226 |
b = self.SubType(a) |
| 227 |
c = array(range(12)).reshape(4,3).view(self.SubType) |
| 228 |
d = c.dot(a) |
| 229 |
assert isinstance(d, self.SubType) |
| 230 |
assert not getattr(d, 'called_new', False) |
| 231 |
assert d.called_finalize |
| 232 |
d = a.dot(c) |
| 233 |
assert not isinstance(d, self.SubType) |
| 234 |
assert not getattr(d, 'called_new', False) |
| 235 |
assert not getattr(d, 'called_finalize', False) |
| 236 |
|
| 237 |
def test_sub_reduce(self): |
| 238 |
|
| 239 |
|
| 240 |
from numpy import array |
| 241 |
a = array(range(12)).reshape(3,4) |
| 242 |
b = self.SubType(a) |
| 243 |
c = b.sum(axis=0) |
| 244 |
assert (c == [12, 15, 18, 21]).all() |
| 245 |
assert isinstance(c, self.SubType) |
| 246 |
assert not getattr(c, 'called_new', False) |
| 247 |
assert c.called_finalize |
| 248 |
d = array(range(4)) |
| 249 |
c = b.sum(axis=0, out=d) |
| 250 |
assert c is d |
| 251 |
assert not isinstance(c, self.SubType) |
| 252 |
d = array(range(4)).view(self.NoNew) |
| 253 |
c = b.sum(axis=0, out=d) |
| 254 |
assert c is d |
| 255 |
assert isinstance(c, self.NoNew) |
| 256 |
|
| 257 |
def test_sub_call2(self): |
| 258 |
|
| 259 |
from numpy import array |
| 260 |
a = array(range(12)).view(self.NoNew) |
| 261 |
b = self.SubType(range(12)) |
| 262 |
c = b + a |
| 263 |
assert isinstance(c, self.SubType) |
| 264 |
c = a + b |
| 265 |
assert isinstance(c, self.NoNew) |
| 266 |
d = range(12) |
| 267 |
e = a - d |
| 268 |
assert isinstance(e, self.NoNew) |
| 269 |
|
| 270 |
def test_sub_call1(self): |
| 271 |
from numpy import array, sqrt |
| 272 |
a = array(range(12)).view(self.NoNew) |
| 273 |
b = sqrt(a) |
| 274 |
assert b.called_finalize == True |
| 275 |
|
| 276 |
def test_sub_astype(self): |
| 277 |
from numpy import array |
| 278 |
a = array(range(12)).view(self.NoNew) |
| 279 |
b = a.astype(float) |
| 280 |
assert b.called_finalize == True |
| 281 |
|
| 282 |
def test_sub_reshape(self): |
| 283 |
from numpy import array |
| 284 |
a = array(range(12)).view(self.NoNew) |
| 285 |
b = a.reshape(3, 4) |
| 286 |
assert b.called_finalize == True |
| 287 |
|
| 288 |
def test___array__(self): |
| 289 |
import sys |
| 290 |
from numpy import ndarray, array, dtype |
| 291 |
class D(ndarray): |
| 292 |
def __new__(subtype, shape, dtype): |
| 293 |
self = ndarray.__new__(subtype, shape, dtype) |
| 294 |
self.id = 'subtype' |
| 295 |
return self |
| 296 |
class C(object): |
| 297 |
def __init__(self, val, dtype): |
| 298 |
self.val = val |
| 299 |
self.dtype = dtype |
| 300 |
def __array__(self, dtype=None): |
| 301 |
retVal = D(self.val, dtype) |
| 302 |
return retVal |
| 303 |
|
| 304 |
a = C([2, 2], int) |
| 305 |
b = array(a, subok=True) |
| 306 |
assert b.shape == (2, 2) |
| 307 |
assert isinstance(b, D) |
| 308 |
c = array(a, float) |
| 309 |
assert c.dtype is dtype(float) |
| 310 |
|
| 311 |
def test_array_of_subtype(self): |
| 312 |
import numpy as np |
| 313 |
|
| 314 |
|
| 315 |
import sys |
| 316 |
if '__pypy__' not in sys.builtin_module_names: |
| 317 |
skip('does not pass on cpython') |
| 318 |
class matrix(np.ndarray): |
| 319 |
def __new__(subtype, data, dtype=None, copy=True): |
| 320 |
print('matrix __new__') |
| 321 |
if isinstance(data, matrix): |
| 322 |
dtype2 = data.dtype |
| 323 |
if (dtype is None): |
| 324 |
dtype = dtype2 |
| 325 |
if (dtype2 == dtype) and (not copy): |
| 326 |
return data |
| 327 |
return data.astype(dtype) |
| 328 |
|
| 329 |
if isinstance(data, np.ndarray): |
| 330 |
if dtype is None: |
| 331 |
intype = data.dtype |
| 332 |
else: |
| 333 |
intype = np.dtype(dtype) |
| 334 |
new = data.view(subtype) |
| 335 |
if intype != data.dtype: |
| 336 |
return new.astype(intype) |
| 337 |
if copy: return new.copy() |
| 338 |
else: return new |
| 339 |
|
| 340 |
if isinstance(data, str): |
| 341 |
data = _convert_from_string(data) |
| 342 |
|
| 343 |
|
| 344 |
arr = np.array(data, dtype=dtype, copy=copy) |
| 345 |
ndim = arr.ndim |
| 346 |
shape = arr.shape |
| 347 |
if (ndim > 2): |
| 348 |
raise ValueError("matrix must be 2-dimensional") |
| 349 |
elif ndim == 0: |
| 350 |
shape = (1, 1) |
| 351 |
elif ndim == 1: |
| 352 |
shape = (1, shape[0]) |
| 353 |
|
| 354 |
order = False |
| 355 |
if (ndim == 2) and arr.flags.fortran: |
| 356 |
order = True |
| 357 |
|
| 358 |
if not (order or arr.flags.contiguous): |
| 359 |
arr = arr.copy() |
| 360 |
|
| 361 |
ret = np.ndarray.__new__(subtype, shape, arr.dtype, |
| 362 |
buffer=arr, |
| 363 |
order=order) |
| 364 |
return ret |
| 365 |
|
| 366 |
def __array_finalize__(self, obj): |
| 367 |
print('matrix __array_finalize__',obj) |
| 368 |
self._getitem = False |
| 369 |
if (isinstance(obj, matrix) and obj._getitem): return |
| 370 |
ndim = self.ndim |
| 371 |
if (ndim == 2): |
| 372 |
return |
| 373 |
if (ndim > 2): |
| 374 |
newshape = tuple([x for x in self.shape if x > 1]) |
| 375 |
ndim = len(newshape) |
| 376 |
if ndim == 2: |
| 377 |
self.shape = newshape |
| 378 |
return |
| 379 |
elif (ndim > 2): |
| 380 |
raise ValueError("shape too large to be a matrix.") |
| 381 |
else: |
| 382 |
newshape = self.shape |
| 383 |
if ndim == 0: |
| 384 |
self.shape = (1, 1) |
| 385 |
elif ndim == 1: |
| 386 |
self.shape = (1, newshape[0]) |
| 387 |
return |
| 388 |
|
| 389 |
def __getitem__(self, index): |
| 390 |
print('matrix __getitem__',index) |
| 391 |
self._getitem = True |
| 392 |
|
| 393 |
try: |
| 394 |
out = np.ndarray.__getitem__(self, index) |
| 395 |
finally: |
| 396 |
self._getitem = False |
| 397 |
|
| 398 |
if not isinstance(out, np.ndarray): |
| 399 |
return out |
| 400 |
|
| 401 |
if out.ndim == 0: |
| 402 |
return out[()] |
| 403 |
if out.ndim == 1: |
| 404 |
sh = out.shape[0] |
| 405 |
|
| 406 |
try: |
| 407 |
n = len(index) |
| 408 |
except: |
| 409 |
n = 0 |
| 410 |
if n > 1 and isscalar(index[1]): |
| 411 |
out.shape = (sh, 1) |
| 412 |
else: |
| 413 |
out.shape = (1, sh) |
| 414 |
return out |
| 415 |
|
| 416 |
a = matrix([[1., 2.], [3., 4.]]) |
| 417 |
b = np.array([a]) |
| 418 |
assert (b == a).all() |
| 419 |
|
| 420 |
b = np.array(a) |
| 421 |
assert len(b.shape) == 2 |
| 422 |
assert (b == a).all() |
| 423 |
|
| 424 |
b = np.array(a, copy=False) |
| 425 |
assert len(b.shape) == 2 |
| 426 |
assert (b == a).all() |
| 427 |
|
| 428 |
b = np.array(a, copy=True, dtype=int) |
| 429 |
assert len(b.shape) == 2 |
| 430 |
assert (b == a).all() |
| 431 |
|
| 432 |
c = matrix(a, copy=False) |
| 433 |
assert c.base is not None |
| 434 |
c[0, 0] = 100 |
| 435 |
assert a[0, 0] == 100 |
| 436 |
b = np.array(c, copy=True) |
| 437 |
assert (b == a).all() |
| 438 |
|
| 439 |
d = np.empty([6,2], dtype=float) |
| 440 |
d.view('int64').fill(0xdeadbeef) |
| 441 |
e = d[0::3,:] |
| 442 |
e[...] = [[1, 2], [3, 4]] |
| 443 |
assert e.strides == (48, 8) |
| 444 |
f = e.view(matrix) |
| 445 |
assert f.strides == (48, 8) |
| 446 |
g = np.array(f, copy=False) |
| 447 |
assert (g == [[1, 2], [3, 4]]).all() |
| 448 |
|
| 449 |
k = np.empty([2, 8], dtype=float) |
| 450 |
k.view('int64').fill(0xdeadbeef) |
| 451 |
m = k[:, ::-4] |
| 452 |
m[...] = [[1, 2], [3, 4]] |
| 453 |
assert m.strides == (64, -32) |
| 454 |
n = m.view(matrix) |
| 455 |
assert n.strides == (64, -32) |
| 456 |
p = np.array(n, copy=False) |
| 457 |
assert (p == [[1, 2], [3, 4]]).all() |
| 458 |
|
| 459 |
|
| 460 |
def test_setstate_no_version(self): |
| 461 |
|
| 462 |
|
| 463 |
from numpy import ndarray, array |
| 464 |
from pickle import loads, dumps |
| 465 |
import sys, new |
| 466 |
class D(ndarray): |
| 467 |
''' A subtype with a constructor that accepts a list of |
| 468 |
data values, where ndarray accepts a shape |
| 469 |
''' |
| 470 |
def __new__(subtype, data, dtype=None, copy=True): |
| 471 |
arr = array(data, dtype=dtype, copy=copy) |
| 472 |
shape = arr.shape |
| 473 |
ret = ndarray.__new__(subtype, shape, arr.dtype, |
| 474 |
buffer=arr, |
| 475 |
order=True) |
| 476 |
return ret |
| 477 |
def __setstate__(self, state): |
| 478 |
(version, shp, typ, isf, raw) = state |
| 479 |
ndarray.__setstate__(self, (shp, typ, isf, raw)) |
| 480 |
|
| 481 |
E = '<' if sys.byteorder == 'little' else '>' |
| 482 |
D.__module__ = 'mod' |
| 483 |
mod = new.module('mod') |
| 484 |
mod.D = D |
| 485 |
sys.modules['mod'] = mod |
| 486 |
a = D([1., 2.]) |
| 487 |
s = dumps(a) |
| 488 |
|
| 489 |
s_from_numpy = '''ignore this line |
| 490 |
_reconstruct |
| 491 |
p0 |
| 492 |
(cmod |
| 493 |
D |
| 494 |
p1 |
| 495 |
(I0 |
| 496 |
tp2 |
| 497 |
S'b' |
| 498 |
p3 |
| 499 |
tp4 |
| 500 |
Rp5 |
| 501 |
(I1 |
| 502 |
(I2 |
| 503 |
tp6 |
| 504 |
cnumpy |
| 505 |
dtype |
| 506 |
p7 |
| 507 |
(S'f8' |
| 508 |
p8 |
| 509 |
I0 |
| 510 |
I1 |
| 511 |
tp9 |
| 512 |
Rp10 |
| 513 |
(I3 |
| 514 |
S'{E}' |
| 515 |
p11 |
| 516 |
NNNI-1 |
| 517 |
I-1 |
| 518 |
I0 |
| 519 |
tp12 |
| 520 |
bI00 |
| 521 |
S'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x00@' |
| 522 |
p13 |
| 523 |
tp14 |
| 524 |
b.'''.replace(' ','').format(E=E) |
| 525 |
for ss,sn in zip(s.split('\n')[1:],s_from_numpy.split('\n')[1:]): |
| 526 |
if len(ss)>10: |
| 527 |
|
| 528 |
continue |
| 529 |
assert ss == sn |
| 530 |
b = loads(s) |
| 531 |
assert (a == b).all() |
| 532 |
assert isinstance(b, D) |
| 533 |
|
| 534 |
def test_subok(self): |
| 535 |
from numpy import array, ndarray |
| 536 |
a = self.SubType(array([[1, 2], [3, 4]])) |
| 537 |
b = array(a, subok=False) |
| 538 |
assert type(b) is ndarray |
| 539 |
|
| 540 |
def test_numpypy_mmap(self): |
| 541 |
|
| 542 |
from numpy import array, ndarray, arange, dtype as dtypedescr |
| 543 |
import mmap |
| 544 |
import os.path |
| 545 |
from tempfile import mkdtemp |
| 546 |
import os.path as path |
| 547 |
valid_filemodes = ["r", "c", "r+", "w+"] |
| 548 |
writeable_filemodes = ["r+", "w+"] |
| 549 |
mode_equivalents = { |
| 550 |
"readonly":"r", |
| 551 |
"copyonwrite":"c", |
| 552 |
"readwrite":"r+", |
| 553 |
"write":"w+" |
| 554 |
} |
| 555 |
|
| 556 |
class memmap(ndarray): |
| 557 |
def __new__(subtype, filename, dtype='uint8', mode='r+', offset=0, shape=None, order='C'): |
| 558 |
|
| 559 |
try: |
| 560 |
mode = mode_equivalents[mode] |
| 561 |
except KeyError: |
| 562 |
if mode not in valid_filemodes: |
| 563 |
raise ValueError("mode must be one of %s" % |
| 564 |
(valid_filemodes + list(mode_equivalents.keys()))) |
| 565 |
|
| 566 |
if hasattr(filename, 'read'): |
| 567 |
fid = filename |
| 568 |
own_file = False |
| 569 |
else: |
| 570 |
fid = open(filename, (mode == 'c' and 'r' or mode)+'b') |
| 571 |
own_file = True |
| 572 |
|
| 573 |
if (mode == 'w+') and shape is None: |
| 574 |
raise ValueError("shape must be given") |
| 575 |
|
| 576 |
fid.seek(0, 2) |
| 577 |
flen = fid.tell() |
| 578 |
descr = dtypedescr(dtype) |
| 579 |
_dbytes = descr.itemsize |
| 580 |
|
| 581 |
if shape is None: |
| 582 |
bytes = flen - offset |
| 583 |
if (bytes % _dbytes): |
| 584 |
fid.close() |
| 585 |
raise ValueError("Size of available data is not a " |
| 586 |
"multiple of the data-type size.") |
| 587 |
size = bytes // _dbytes |
| 588 |
shape = (size,) |
| 589 |
else: |
| 590 |
if not isinstance(shape, tuple): |
| 591 |
shape = (shape,) |
| 592 |
size = 1 |
| 593 |
for k in shape: |
| 594 |
size *= k |
| 595 |
|
| 596 |
bytes = long(offset + size*_dbytes) |
| 597 |
|
| 598 |
if mode == 'w+' or (mode == 'r+' and flen < bytes): |
| 599 |
fid.seek(bytes - 1, 0) |
| 600 |
fid.write('\0') |
| 601 |
fid.flush() |
| 602 |
|
| 603 |
if mode == 'c': |
| 604 |
acc = mmap.ACCESS_COPY |
| 605 |
elif mode == 'r': |
| 606 |
acc = mmap.ACCESS_READ |
| 607 |
else: |
| 608 |
acc = mmap.ACCESS_WRITE |
| 609 |
|
| 610 |
start = offset - offset % mmap.ALLOCATIONGRANULARITY |
| 611 |
bytes -= start |
| 612 |
offset -= start |
| 613 |
mm = mmap.mmap(fid.fileno(), bytes, access=acc, offset=start) |
| 614 |
|
| 615 |
self = ndarray.__new__(subtype, shape, dtype=descr, buffer=mm, |
| 616 |
offset=offset, order=order) |
| 617 |
self._mmap = mm |
| 618 |
self.offset = offset |
| 619 |
self.mode = mode |
| 620 |
|
| 621 |
if isinstance(filename, basestring): |
| 622 |
self.filename = os.path.abspath(filename) |
| 623 |
|
| 624 |
elif (hasattr(filename, "name") and |
| 625 |
isinstance(filename.name, basestring)): |
| 626 |
self.filename = os.path.abspath(filename.name) |
| 627 |
|
| 628 |
else: |
| 629 |
self.filename = None |
| 630 |
|
| 631 |
if own_file: |
| 632 |
fid.close() |
| 633 |
|
| 634 |
return self |
| 635 |
|
| 636 |
def flush(self): |
| 637 |
if self.base is not None and hasattr(self.base, 'flush'): |
| 638 |
self.base.flush() |
| 639 |
|
| 640 |
def asarray(obj, itemsize=None, order=None): |
| 641 |
return array(obj, itemsize, copy=False, order=order) |
| 642 |
|
| 643 |
filename = path.join(mkdtemp(), 'newfile.dat') |
| 644 |
data = arange(10*10*36).reshape(10, 10, 36) |
| 645 |
fp = memmap(filename, dtype='float32', mode='w+', shape=data.shape) |
| 646 |
vals = [ 242, 507, 255, 505, 315, 316, 308, 506, |
| 647 |
309, 255, 211, 505, 315, 316, 308, 506, |
| 648 |
309, 255, 255, 711, 194, 232, 711, 711, |
| 649 |
709, 710, 709, 710, 882, 897, 711, 245, |
| 650 |
711, 711, 168, 245] |
| 651 |
fp[:] = data |
| 652 |
fp[5:6][:,4] = vals |
| 653 |
a = asarray(fp[5:6][:,4]) |
| 654 |
assert (a == vals).all() |
| 655 |
|
| 656 |
def test__array_wrap__(self): |
| 657 |
''' Straight from the documentation of __array_wrap__ |
| 658 |
''' |
| 659 |
import numpy as np |
| 660 |
|
| 661 |
class MySubClass(np.ndarray): |
| 662 |
output = '' |
| 663 |
|
| 664 |
def __new__(cls, input_array, info=None): |
| 665 |
obj = np.array(input_array).view(cls) |
| 666 |
obj.info = info |
| 667 |
return obj |
| 668 |
|
| 669 |
def __array_finalize__(self, obj): |
| 670 |
self.output += 'In __array_finalize__:' |
| 671 |
self.output += ' self is %s' % repr(self) |
| 672 |
self.output += ' obj is %s\n' % repr(obj) |
| 673 |
print self.output |
| 674 |
if obj is None: return |
| 675 |
self.info = getattr(obj, 'info', None) |
| 676 |
|
| 677 |
def __array_wrap__(self, out_arr, context=None): |
| 678 |
self.output += 'In __array_wrap__:' |
| 679 |
self.output += ' self is %s' % repr(self) |
| 680 |
self.output += ' arr is %r\n' % (out_arr,) |
| 681 |
self.output += ' context is %r\n' % (context,) |
| 682 |
|
| 683 |
ret = np.ndarray.__array_wrap__(self, out_arr, context) |
| 684 |
print 'wrap',self.output |
| 685 |
return ret |
| 686 |
|
| 687 |
obj = MySubClass(np.arange(5), info='spam') |
| 688 |
assert obj.output.startswith('In __array_finalize') |
| 689 |
obj.output = '' |
| 690 |
print 'np.arange(5) + 1' |
| 691 |
arr2 = np.arange(5) + 1 |
| 692 |
assert len(obj.output) < 1 |
| 693 |
print 'np.add(arr2, obj)' |
| 694 |
ret = np.add(arr2, obj) |
| 695 |
assert obj.output.startswith('In __array_wrap') |
| 696 |
assert 'finalize' not in obj.output |
| 697 |
assert ret.info == 'spam' |
| 698 |
print 'np.negative(obj)' |
| 699 |
ret = np.negative(obj) |
| 700 |
assert ret.info == 'spam' |
| 701 |
print 'obj.sum()' |
| 702 |
ret = obj.sum() |
| 703 |
print type(ret) |
| 704 |
assert ret.info == 'spam' |
| 705 |
|
| 706 |
def test_ndarray_subclass_assigns_base(self): |
| 707 |
import numpy as np |
| 708 |
init_called = [] |
| 709 |
class _DummyArray(object): |
| 710 |
""" Dummy object that just exists to hang __array_interface__ dictionaries |
| 711 |
and possibly keep alive a reference to a base array. |
| 712 |
""" |
| 713 |
def __init__(self, interface, base=None): |
| 714 |
self.__array_interface__ = interface |
| 715 |
init_called.append(1) |
| 716 |
self.base = base |
| 717 |
|
| 718 |
x = np.zeros(10) |
| 719 |
d = _DummyArray(x.__array_interface__, base=x) |
| 720 |
y = np.array(d, copy=False) |
| 721 |
assert sum(init_called) == 1 |
| 722 |
assert y.base is d |
| 723 |
|
| 724 |
x = np.zeros((0,), dtype='float32') |
| 725 |
intf = x.__array_interface__.copy() |
| 726 |
intf["strides"] = x.strides |
| 727 |
x.__array_interface__["strides"] = x.strides |
| 728 |
d = _DummyArray(x.__array_interface__, base=x) |
| 729 |
y = np.array(d, copy=False) |
| 730 |
assert sum(init_called) == 2 |
| 731 |
assert y.base is d |
| 732 |
|
| 733 |
|