Return random structure: (memlen, itemsize, ndim, shape, strides, offset) If 'valid' is true, the returned structure is valid, otherwise invalid. If 'shape' is given, use that instead of creating a random shape.
(itemsize, valid, maxdim=5, maxshape=16, shape=())
| 494 | return False |
| 495 | |
| 496 | def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()): |
| 497 | """Return random structure: |
| 498 | (memlen, itemsize, ndim, shape, strides, offset) |
| 499 | If 'valid' is true, the returned structure is valid, otherwise invalid. |
| 500 | If 'shape' is given, use that instead of creating a random shape. |
| 501 | """ |
| 502 | if not shape: |
| 503 | ndim = randrange(maxdim+1) |
| 504 | if (ndim == 0): |
| 505 | if valid: |
| 506 | return itemsize, itemsize, ndim, (), (), 0 |
| 507 | else: |
| 508 | nitems = randrange(1, 16+1) |
| 509 | memlen = nitems * itemsize |
| 510 | offset = -itemsize if randrange(2) == 0 else memlen |
| 511 | return memlen, itemsize, ndim, (), (), offset |
| 512 | |
| 513 | minshape = 2 |
| 514 | n = randrange(100) |
| 515 | if n >= 95 and valid: |
| 516 | minshape = 0 |
| 517 | elif n >= 90: |
| 518 | minshape = 1 |
| 519 | shape = [0] * ndim |
| 520 | |
| 521 | for i in range(ndim): |
| 522 | shape[i] = randrange(minshape, maxshape+1) |
| 523 | else: |
| 524 | ndim = len(shape) |
| 525 | |
| 526 | maxstride = 5 |
| 527 | n = randrange(100) |
| 528 | zero_stride = True if n >= 95 and n & 1 else False |
| 529 | |
| 530 | strides = [0] * ndim |
| 531 | strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1) |
| 532 | if not zero_stride and strides[ndim-1] == 0: |
| 533 | strides[ndim-1] = itemsize |
| 534 | |
| 535 | for i in range(ndim-2, -1, -1): |
| 536 | maxstride *= shape[i+1] if shape[i+1] else 1 |
| 537 | if zero_stride: |
| 538 | strides[i] = itemsize * randrange(-maxstride, maxstride+1) |
| 539 | else: |
| 540 | strides[i] = ((1,-1)[randrange(2)] * |
| 541 | itemsize * randrange(1, maxstride+1)) |
| 542 | |
| 543 | imin = imax = 0 |
| 544 | if not 0 in shape: |
| 545 | imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) |
| 546 | if strides[j] <= 0) |
| 547 | imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) |
| 548 | if strides[j] > 0) |
| 549 | |
| 550 | nitems = imax - imin |
| 551 | if valid: |
| 552 | offset = -imin * itemsize |
| 553 | memlen = offset + (imax+1) * itemsize |
no test coverage detected