field.py 25 KB
Newer Older
1
from enum import Enum
2
from itertools import chain
Martin Bauer's avatar
Martin Bauer committed
3
from typing import Tuple, Sequence, Optional, List
4
5
6
7
import numpy as np
import sympy as sp
from sympy.core.cache import cacheit
from sympy.tensor import IndexedBase
8
from pystencils.alignedarray import aligned_empty
Martin Bauer's avatar
Martin Bauer committed
9
from pystencils.data_types import TypedSymbol, create_type, create_composite_type_from_string, StructType
Martin Bauer's avatar
Martin Bauer committed
10
from pystencils.sympyextensions import is_integer_sequence
11
12


13
14
15
16
17
18
19
20
21
22
class FieldType(Enum):
    # generic fields
    GENERIC = 0
    # index fields are currently only used for boundary handling
    # the coordinates are not the loop counters in that case, but are read from this index field
    INDEXED = 1
    # communication buffer, used for (un)packing data in communication.
    BUFFER = 2

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
23
    def is_generic(field):
24
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
25
        return field.field_type == FieldType.GENERIC
26
27

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
28
    def is_indexed(field):
29
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
30
        return field.field_type == FieldType.INDEXED
31
32

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
33
    def is_buffer(field):
34
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
35
        return field.field_type == FieldType.BUFFER
36
37


38
class Field:
39
40
41
42
    """
    With fields one can formulate stencil-like update rules on structured grids.
    This Field class knows about the dimension, memory layout (strides) and optionally about the size of an array.

Martin Bauer's avatar
Martin Bauer committed
43
44
45
46
    Creating Fields:

        To create a field use one of the static create* members. There are two options:

47
        1. create a kernel with fixed loop sizes i.e. the shape of the array is already known. This is usually the
Martin Bauer's avatar
Martin Bauer committed
48
           case if just-in-time compilation directly from Python is done. (see :func:`Field.create_from_numpy_array`)
49
        2. create a more general kernel that works for variable array sizes. This can be used to create kernels
Martin Bauer's avatar
Martin Bauer committed
50
           beforehand for a library. (see :func:`Field.create_generic`)
51
52
53
54

    Dimensions:
        A field has spatial and index dimensions, where the spatial dimensions come first.
        The interpretation is that the field has multiple cells in (usually) two or three dimensional space which are
Martin Bauer's avatar
Martin Bauer committed
55
56
        looped over. Additionally  N values are stored per cell. In this case spatial_dimensions is two or three,
        and index_dimensions equals N. If you want to store a matrix on each point in a two dimensional grid, there
Martin Bauer's avatar
Martin Bauer committed
57
        are four dimensions, two spatial and two index dimensions: ``len(arr.shape) == spatial_dims + index_dims``
58
59
60

    Indexing:
        When accessing (indexing) a field the result is a FieldAccess which is derived from sympy Symbol.
Martin Bauer's avatar
Martin Bauer committed
61
        First specify the spatial offsets in [], then in case index_dimension>0 the indices in ()
Martin Bauer's avatar
Martin Bauer committed
62
        e.g. ``f[-1,0,0](7)``
63
64
65

    Example without index dimensions:
        >>> a = np.zeros([10, 10])
Martin Bauer's avatar
Martin Bauer committed
66
        >>> f = Field.create_from_numpy_array("f", a, index_dimensions=0)
67
68
69
        >>> jacobi = ( f[-1,0] + f[1,0] + f[0,-1] + f[0,1] ) / 4

    Example with index dimensions: LBM D2Q9 stream pull
Martin Bauer's avatar
Martin Bauer committed
70
        >>> from pystencils import Assignment
71
        >>> stencil = np.array([[0,0], [0,1], [0,-1]])
Martin Bauer's avatar
Martin Bauer committed
72
73
        >>> src = Field.create_generic("src", spatial_dimensions=2, index_dimensions=1)
        >>> dst = Field.create_generic("dst", spatial_dimensions=2, index_dimensions=1)
74
        >>> for i, offset in enumerate(stencil):
75
76
77
78
        ...     Assignment(dst[0,0](i), src[-offset](i))
        Assignment(dst_C^0, src_C^0)
        Assignment(dst_C^1, src_S^1)
        Assignment(dst_C^2, src_N^2)
79
    """
80
81

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
82
83
    def create_generic(field_name, spatial_dimensions, dtype=np.float64, index_dimensions=0, layout='numpy',
                       index_shape=None, field_type=FieldType.GENERIC) -> 'Field':
84
85
86
        """
        Creates a generic field where the field size is not fixed i.e. can be called with arrays of different sizes

Martin Bauer's avatar
Martin Bauer committed
87
88
89
90
91
92
93
        Args:
            field_name: symbolic name for the field
            dtype: numpy data type of the array the kernel is called with later
            spatial_dimensions: see documentation of Field
            index_dimensions: see documentation of Field
            layout: tuple specifying the loop ordering of the spatial dimensions e.g. (2, 1, 0 ) means that
                    the outer loop loops over dimension 2, the second outer over dimension 1, and the inner loop
Martin Bauer's avatar
Martin Bauer committed
94
                    over dimension 0. Also allowed: the strings 'numpy' (0,1,..d) or 'reverse_numpy' (d, ..., 1, 0)
Martin Bauer's avatar
Martin Bauer committed
95
96
97
98
99
            index_shape: optional shape of the index dimensions i.e. maximum values allowed for each index dimension,
                        has to be a list or tuple
            field_type: besides the normal GENERIC fields, there are INDEXED fields that store indices of the domain
                        that should be iterated over, and BUFFER fields that are used to generate
                        communication packing/unpacking kernels
100
        """
101
        if isinstance(layout, str):
Martin Bauer's avatar
Martin Bauer committed
102
103
104
105
106
107
            layout = spatial_layout_string_to_tuple(layout, dim=spatial_dimensions)
        shape_symbol = IndexedBase(TypedSymbol(Field.SHAPE_PREFIX + field_name, Field.SHAPE_DTYPE), shape=(1,))
        stride_symbol = IndexedBase(TypedSymbol(Field.STRIDE_PREFIX + field_name, Field.STRIDE_DTYPE), shape=(1,))
        total_dimensions = spatial_dimensions + index_dimensions
        if index_shape is None or len(index_shape) == 0:
            shape = tuple([shape_symbol[i] for i in range(total_dimensions)])
108
        else:
Martin Bauer's avatar
Martin Bauer committed
109
            shape = tuple([shape_symbol[i] for i in range(spatial_dimensions)] + list(index_shape))
110

Martin Bauer's avatar
Martin Bauer committed
111
        strides = tuple([stride_symbol[i] for i in range(total_dimensions)])
112

Martin Bauer's avatar
Martin Bauer committed
113
114
115
        np_data_type = np.dtype(dtype)
        if np_data_type.fields is not None:
            if index_dimensions != 0:
116
117
118
119
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

Martin Bauer's avatar
Martin Bauer committed
120
        return Field(field_name, field_type, dtype, layout, shape, strides)
121

122
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
123
124
125
    def create_from_numpy_array(field_name: str, array: np.ndarray, index_dimensions: int = 0) -> 'Field':
        """Creates a field based on the layout, data type, and shape of a given numpy array.

126
        Kernels created for these kind of fields can only be called with arrays of the same layout, shape and type.
Martin Bauer's avatar
Martin Bauer committed
127
128
129
130
131

        Args:
            field_name: symbolic name for the field
            array: numpy array
            index_dimensions: see documentation of Field
132
        """
Martin Bauer's avatar
Martin Bauer committed
133
134
        spatial_dimensions = len(array.shape) - index_dimensions
        if spatial_dimensions < 1:
135
136
            raise ValueError("Too many index dimensions. At least one spatial dimension required")

Martin Bauer's avatar
Martin Bauer committed
137
138
139
        full_layout = get_layout_of_array(array)
        spatial_layout = tuple([i for i in full_layout if i < spatial_dimensions])
        assert len(spatial_layout) == spatial_dimensions
140

Martin Bauer's avatar
Martin Bauer committed
141
142
        strides = tuple([s // np.dtype(array.dtype).itemsize for s in array.strides])
        shape = tuple(int(s) for s in array.shape)
143

Martin Bauer's avatar
Martin Bauer committed
144
145
146
        numpy_dtype = np.dtype(array.dtype)
        if numpy_dtype.fields is not None:
            if index_dimensions != 0:
147
148
149
150
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

Martin Bauer's avatar
Martin Bauer committed
151
        return Field(field_name, FieldType.GENERIC, array.dtype, spatial_layout, shape, strides)
152
153

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
154
    def create_fixed_size(field_name: str, shape: Tuple[int, ...], index_dimensions: int = 0,
155
                          dtype=np.float64, layout: str = 'numpy', strides: Optional[Sequence[int]] = None) -> 'Field':
156
        """
157
        Creates a field with fixed sizes i.e. can be called only with arrays of the same size and layout
158

Martin Bauer's avatar
Martin Bauer committed
159
160
161
162
163
164
165
        Args:
            field_name: symbolic name for the field
            shape: overall shape of the array
            index_dimensions: how many of the trailing dimensions are interpreted as index (as opposed to spatial)
            dtype: numpy data type of the array the kernel is called with later
            layout: full layout of array, not only spatial dimensions
            strides: strides in bytes or None to automatically compute them from shape (assuming no padding)
166
        """
Martin Bauer's avatar
Martin Bauer committed
167
168
        spatial_dimensions = len(shape) - index_dimensions
        assert spatial_dimensions >= 1
169

170
        if isinstance(layout, str):
Martin Bauer's avatar
Martin Bauer committed
171
            layout = layout_string_to_tuple(layout, spatial_dimensions + index_dimensions)
172
173

        shape = tuple(int(s) for s in shape)
174
        if strides is None:
Martin Bauer's avatar
Martin Bauer committed
175
            strides = compute_strides(shape, layout)
176
177
178
        else:
            assert len(strides) == len(shape)
            strides = tuple([s // np.dtype(dtype).itemsize for s in strides])
179

Martin Bauer's avatar
Martin Bauer committed
180
181
182
        numpy_dtype = np.dtype(dtype)
        if numpy_dtype.fields is not None:
            if index_dimensions != 0:
183
184
185
186
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

Martin Bauer's avatar
Martin Bauer committed
187
188
189
190
        spatial_layout = list(layout)
        for i in range(spatial_dimensions, len(layout)):
            spatial_layout.remove(i)
        return Field(field_name, FieldType.GENERIC, dtype, tuple(spatial_layout), shape, strides)
191

Martin Bauer's avatar
Martin Bauer committed
192
    def __init__(self, field_name, field_type, dtype, layout, shape, strides):
193
        """Do not use directly. Use static create* methods"""
194
        self._field_name = field_name
Martin Bauer's avatar
Martin Bauer committed
195
        assert isinstance(field_type, FieldType)
Martin Bauer's avatar
Martin Bauer committed
196
        self.field_type = field_type
Martin Bauer's avatar
Martin Bauer committed
197
        self._dtype = create_type(dtype)
Martin Bauer's avatar
Martin Bauer committed
198
        self._layout = normalize_layout(layout)
199
200
        self.shape = shape
        self.strides = strides
Martin Bauer's avatar
Martin Bauer committed
201
        self.latex_name: Optional[str] = None
202

Martin Bauer's avatar
Martin Bauer committed
203
    def new_field_with_different_name(self, new_name):
Martin Bauer's avatar
Martin Bauer committed
204
        return Field(new_name, self.field_type, self._dtype, self._layout, self.shape, self.strides)
205

206
    @property
Martin Bauer's avatar
Martin Bauer committed
207
    def spatial_dimensions(self) -> int:
208
209
210
        return len(self._layout)

    @property
Martin Bauer's avatar
Martin Bauer committed
211
    def index_dimensions(self) -> int:
212
        return len(self.shape) - len(self._layout)
213
214
215
216
217
218

    @property
    def layout(self):
        return self._layout

    @property
Martin Bauer's avatar
Martin Bauer committed
219
    def name(self) -> str:
220
        return self._field_name
221
222

    @property
Martin Bauer's avatar
Martin Bauer committed
223
224
    def spatial_shape(self) -> Tuple[int, ...]:
        return self.shape[:self.spatial_dimensions]
225

226
    @property
Martin Bauer's avatar
Martin Bauer committed
227
    def has_fixed_shape(self):
Martin Bauer's avatar
Martin Bauer committed
228
        return is_integer_sequence(self.shape)
229

230
    @property
Martin Bauer's avatar
Martin Bauer committed
231
232
    def index_shape(self):
        return self.shape[self.spatial_dimensions:]
233

234
    @property
Martin Bauer's avatar
Martin Bauer committed
235
236
    def has_fixed_index_shape(self):
        return is_integer_sequence(self.index_shape)
237

238
    @property
Martin Bauer's avatar
Martin Bauer committed
239
240
    def spatial_strides(self):
        return self.strides[:self.spatial_dimensions]
241
242

    @property
Martin Bauer's avatar
Martin Bauer committed
243
244
    def index_strides(self):
        return self.strides[self.spatial_dimensions:]
245
246
247
248
249
250

    @property
    def dtype(self):
        return self._dtype

    def __repr__(self):
251
        return self._field_name
252

Martin Bauer's avatar
Martin Bauer committed
253
254
255
256
    def neighbor(self, coord_id, offset):
        offset_list = [0] * self.spatial_dimensions
        offset_list[coord_id] = offset
        return Field.Access(self, tuple(offset_list))
257

258
    def neighbors(self, stencil):
259
        return [self.__getitem__(s) for s in stencil]
260

261
    @property
Martin Bauer's avatar
Martin Bauer committed
262
263
264
    def center_vector(self):
        index_shape = self.index_shape
        if len(index_shape) == 0:
265
            return self.center
Martin Bauer's avatar
Martin Bauer committed
266
267
268
        elif len(index_shape) == 1:
            return sp.Matrix([self(i) for i in range(index_shape[0])])
        elif len(index_shape) == 2:
269
270
271
            def cb(*args):
                r = self.__call__(*args)
                return r
Martin Bauer's avatar
Martin Bauer committed
272
            return sp.Matrix(*index_shape, cb)
273

274
    @property
275
    def center(self):
Martin Bauer's avatar
Martin Bauer committed
276
        center = tuple([0] * self.spatial_dimensions)
277
278
        return Field.Access(self, center)

279
280
281
282
    def __getitem__(self, offset):
        if type(offset) is np.ndarray:
            offset = tuple(offset)
        if type(offset) is str:
Martin Bauer's avatar
Martin Bauer committed
283
            offset = tuple(direction_string_to_offset(offset, self.spatial_dimensions))
284
285
        if type(offset) is not tuple:
            offset = (offset,)
Martin Bauer's avatar
Martin Bauer committed
286
        if len(offset) != self.spatial_dimensions:
287
            raise ValueError("Wrong number of spatial indices: "
Martin Bauer's avatar
Martin Bauer committed
288
                             "Got %d, expected %d" % (len(offset), self.spatial_dimensions))
289
290
291
        return Field.Access(self, offset)

    def __call__(self, *args, **kwargs):
Martin Bauer's avatar
Martin Bauer committed
292
        center = tuple([0] * self.spatial_dimensions)
293
294
295
        return Field.Access(self, center)(*args, **kwargs)

    def __hash__(self):
296
        return hash((self._layout, self.shape, self.strides, self._dtype, self.field_type, self._field_name))
297
298

    def __eq__(self, other):
Martin Bauer's avatar
Martin Bauer committed
299
300
        self_tuple = (self.shape, self.strides, self.name, self.dtype, self.field_type)
        other_tuple = (other.shape, other.strides, other.name, other.dtype, other.field_type)
Martin Bauer's avatar
Martin Bauer committed
301
        return self_tuple == other_tuple
302

303
304
305
    PREFIX = "f"
    STRIDE_PREFIX = PREFIX + "stride_"
    SHAPE_PREFIX = PREFIX + "shape_"
Martin Bauer's avatar
Martin Bauer committed
306
307
    STRIDE_DTYPE = create_composite_type_from_string("const int *")
    SHAPE_DTYPE = create_composite_type_from_string("const int *")
308
    DATA_PREFIX = PREFIX + "d_"
309

Martin Bauer's avatar
Martin Bauer committed
310
    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
311
312
313
314
315
316
    class Access(sp.Symbol):
        def __new__(cls, name, *args, **kwargs):
            obj = Field.Access.__xnew_cached_(cls, name, *args, **kwargs)
            return obj

        def __new_stage2__(self, field, offsets=(0, 0, 0), idx=None):
Martin Bauer's avatar
Martin Bauer committed
317
318
319
            field_name = field.name
            offsets_and_index = chain(offsets, idx) if idx is not None else offsets
            constant_offsets = not any([isinstance(o, sp.Basic) and not o.is_Integer for o in offsets_and_index])
320
321

            if not idx:
Martin Bauer's avatar
Martin Bauer committed
322
                idx = tuple([0] * field.index_dimensions)
323

Martin Bauer's avatar
Martin Bauer committed
324
325
326
            if constant_offsets:
                offset_name = offset_to_direction_string(offsets)
                if field.index_dimensions == 0:
327
                    superscript = None
Martin Bauer's avatar
Martin Bauer committed
328
                elif field.index_dimensions == 1:
329
                    superscript = str(idx[0])
330
                else:
Martin Bauer's avatar
Martin Bauer committed
331
332
333
334
                    idx_str = ",".join([str(e) for e in idx])
                    superscript = idx_str
                if field.has_fixed_index_shape and not isinstance(field.dtype, StructType):
                    for i, bound in zip(idx, field.index_shape):
335
336
                        if i >= bound:
                            raise ValueError("Field index out of bounds")
337
            else:
Martin Bauer's avatar
Martin Bauer committed
338
                offset_name = "%0.10X" % (abs(hash(tuple(offsets_and_index))))
339
                superscript = None
340

Martin Bauer's avatar
Martin Bauer committed
341
            symbol_name = "%s_%s" % (field_name, offset_name)
342
            if superscript is not None:
Martin Bauer's avatar
Martin Bauer committed
343
                symbol_name += "^" + superscript
344

Martin Bauer's avatar
Martin Bauer committed
345
            obj = super(Field.Access, self).__xnew__(self, symbol_name)
346
347
348
349
350
351
352
            obj._field = field
            obj._offsets = []
            for o in offsets:
                if isinstance(o, sp.Basic):
                    obj._offsets.append(o)
                else:
                    obj._offsets.append(int(o))
Martin Bauer's avatar
Martin Bauer committed
353
            obj._offsetName = offset_name
354
            obj._superscript = superscript
355
356
357
358
            obj._index = idx

            return obj

359
        def __getnewargs__(self):
360
            return self.field, self.offsets, self.index
361

Martin Bauer's avatar
Martin Bauer committed
362
        # noinspection SpellCheckingInspection
363
        __xnew__ = staticmethod(__new_stage2__)
Martin Bauer's avatar
Martin Bauer committed
364
        # noinspection SpellCheckingInspection
365
366
367
        __xnew_cached_ = staticmethod(cacheit(__new_stage2__))

        def __call__(self, *idx):
Martin Bauer's avatar
Martin Bauer committed
368
            if self._index != tuple([0] * self.field.index_dimensions):
369
370
371
                raise ValueError("Indexing an already indexed Field.Access")

            idx = tuple(idx)
372

Martin Bauer's avatar
Martin Bauer committed
373
            if self.field.index_dimensions == 0 and idx == (0,):
374
375
                idx = ()

Martin Bauer's avatar
Martin Bauer committed
376
            if len(idx) != self.field.index_dimensions:
377
                raise ValueError("Wrong number of indices: "
Martin Bauer's avatar
Martin Bauer committed
378
                                 "Got %d, expected %d" % (len(idx), self.field.index_dimensions))
379
380
            return Field.Access(self.field, self._offsets, idx)

Martin Bauer's avatar
Martin Bauer committed
381
382
383
        def __getitem__(self, *idx):
            return self.__call__(*idx)

Martin Bauer's avatar
Martin Bauer committed
384
385
386
387
388
        def __iter__(self):
            """This is necessary to work with parts of sympy that test if an object is iterable (e.g. simplify).
            The __getitem__ would make it iterable"""
            raise TypeError("Field access is not iterable")

389
390
391
392
393
394
        @property
        def field(self):
            return self._field

        @property
        def offsets(self):
395
            return tuple(self._offsets)
396

397
        @property
Martin Bauer's avatar
Martin Bauer committed
398
        def required_ghost_layers(self):
399
400
401
            return int(np.max(np.abs(self._offsets)))

        @property
Martin Bauer's avatar
Martin Bauer committed
402
        def nr_of_coordinates(self):
403
404
405
            return len(self._offsets)

        @property
Martin Bauer's avatar
Martin Bauer committed
406
        def offset_name(self) -> str:
407
408
409
410
411
412
            return self._offsetName

        @property
        def index(self):
            return self._index

Martin Bauer's avatar
Martin Bauer committed
413
414
415
416
        def neighbor(self, coord_id: int, offset: Sequence[int]) -> 'Field.Access':
            offset_list = list(self.offsets)
            offset_list[coord_id] += offset
            return Field.Access(self.field, tuple(offset_list), self.index)
417

Martin Bauer's avatar
Martin Bauer committed
418
        def get_shifted(self, *shift)-> 'Field.Access':
419
420
            return Field.Access(self.field, tuple(a + b for a, b in zip(shift, self.offsets)), self.index)

421
        def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
422
423
            super_class_contents = list(super(Field.Access, self)._hashable_content())
            t = tuple(super_class_contents + [hash(self._field), self._index] + self._offsets)
424
            return t
Martin Bauer's avatar
Martin Bauer committed
425

Martin Bauer's avatar
Martin Bauer committed
426
        def _latex(self, _):
427
            n = self._field.latex_name if self._field.latex_name else self._field.name
Martin Bauer's avatar
Martin Bauer committed
428
429
430
431
            if self._superscript:
                return "{{%s}_{%s}^{%s}}" % (n, self._offsetName, self._superscript)
            else:
                return "{{%s}_{%s}}" % (n, self._offsetName)
Martin Bauer's avatar
Martin Bauer committed
432
433


Martin Bauer's avatar
Martin Bauer committed
434
435
def get_layout_from_strides(strides: Sequence[int], index_dimension_ids: Optional[List[int]] = None):
    index_dimension_ids = [] if index_dimension_ids is None else index_dimension_ids
436
    coordinates = list(range(len(strides)))
Martin Bauer's avatar
Martin Bauer committed
437
    relevant_strides = [stride for i, stride in enumerate(strides) if i not in index_dimension_ids]
438
    result = [x for (y, x) in sorted(zip(relevant_strides, coordinates), key=lambda pair: pair[0], reverse=True)]
Martin Bauer's avatar
Martin Bauer committed
439
    return normalize_layout(result)
440
441


Martin Bauer's avatar
Martin Bauer committed
442
443
444
445
446
447
def get_layout_of_array(arr: np.ndarray, index_dimension_ids: Optional[List[int]] = None):
    """ Returns a list indicating the memory layout (linearization order) of the numpy array.

    Examples:
        >>> get_layout_of_array(np.zeros([3,3,3]))
        (0, 1, 2)
Martin Bauer's avatar
Martin Bauer committed
448
449
450
451
452

    In this example the loop over the zeroth coordinate should be the outermost loop,
    followed by the first and second. Elements arr[x,y,0] and arr[x,y,1] are adjacent in memory.
    Normally constructed numpy arrays have this order, however by stride tricks or other frameworks, arrays
    with different memory layout can be created.
Martin Bauer's avatar
Martin Bauer committed
453

Martin Bauer's avatar
Martin Bauer committed
454
    The index_dimension_ids parameter leaves specifies which coordinates should not be
Martin Bauer's avatar
Martin Bauer committed
455
    """
Martin Bauer's avatar
Martin Bauer committed
456
457
    index_dimension_ids = [] if index_dimension_ids is None else index_dimension_ids
    return get_layout_from_strides(arr.strides, index_dimension_ids)
458
459


Martin Bauer's avatar
Martin Bauer committed
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def create_numpy_array_with_layout(shape, layout, alignment=False, byte_offset=0, **kwargs):
    """Creates numpy array with given memory layout.

    Args:
        shape: shape of the resulting array
        layout: layout as tuple, where the coordinates are ordered from slow to fast
        alignment: number of bytes to align the beginning and the innermost coordinate to, or False for no alignment
        byte_offset: only used when alignment is specified, align not beginning but address at this offset
                     mostly used to align first inner cell, not ghost cells

    Example:
        >>> res = create_numpy_array_with_layout(shape=(2, 3, 4, 5), layout=(3, 2, 0, 1))
        >>> res.shape
        (2, 3, 4, 5)
        >>> get_layout_of_array(res)
        (3, 2, 0, 1)
476
477
    """
    assert set(layout) == set(range(len(shape))), "Wrong layout descriptor"
Martin Bauer's avatar
Martin Bauer committed
478
    cur_layout = list(range(len(shape)))
479
480
    swaps = []
    for i in range(len(layout)):
Martin Bauer's avatar
Martin Bauer committed
481
482
483
484
485
        if cur_layout[i] != layout[i]:
            index_to_swap_with = cur_layout.index(layout[i])
            swaps.append((i, index_to_swap_with))
            cur_layout[i], cur_layout[index_to_swap_with] = cur_layout[index_to_swap_with], cur_layout[i]
    assert tuple(cur_layout) == tuple(layout)
486
487
488
489
490

    shape = list(shape)
    for a, b in swaps:
        shape[a], shape[b] = shape[b], shape[a]

491
492
493
494
495
    if not alignment:
        res = np.empty(shape, order='c', **kwargs)
    else:
        if alignment is True:
            alignment = 8 * 4
Martin Bauer's avatar
Martin Bauer committed
496
        res = aligned_empty(shape, alignment, byte_offset=byte_offset, **kwargs)
497

498
499
500
501
502
    for a, b in reversed(swaps):
        res = res.swapaxes(a, b)
    return res


Martin Bauer's avatar
Martin Bauer committed
503
504
def spatial_layout_string_to_tuple(layout_str: str, dim: int) -> Tuple[int, ...]:
    if layout_str in ('fzyx', 'zyxf'):
505
506
        assert dim <= 3
        return tuple(reversed(range(dim)))
507

Martin Bauer's avatar
Martin Bauer committed
508
    if layout_str in ('fzyx', 'f', 'reverse_numpy', 'SoA'):
509
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
510
    elif layout_str in ('c', 'numpy', 'AoS'):
511
        return tuple(range(dim))
Martin Bauer's avatar
Martin Bauer committed
512
    raise ValueError("Unknown layout descriptor " + layout_str)
513
514


Martin Bauer's avatar
Martin Bauer committed
515
516
517
def layout_string_to_tuple(layout_str, dim):
    layout_str = layout_str.lower()
    if layout_str == 'fzyx' or layout_str == 'soa':
518
519
        assert dim <= 4
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
520
    elif layout_str == 'zyxf' or layout_str == 'aos':
521
        assert dim <= 4
Martin Bauer's avatar
Martin Bauer committed
522
        return tuple(reversed(range(dim - 1))) + (dim - 1,)
Martin Bauer's avatar
Martin Bauer committed
523
    elif layout_str == 'f' or layout_str == 'reverse_numpy':
524
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
525
    elif layout_str == 'c' or layout_str == 'numpy':
526
        return tuple(range(dim))
Martin Bauer's avatar
Martin Bauer committed
527
    raise ValueError("Unknown layout descriptor " + layout_str)
528
529


Martin Bauer's avatar
Martin Bauer committed
530
def normalize_layout(layout):
531
    """Takes a layout tuple and subtracts the minimum from all entries"""
Martin Bauer's avatar
Martin Bauer committed
532
533
    min_entry = min(layout)
    return tuple(i - min_entry for i in layout)
534
535


Martin Bauer's avatar
Martin Bauer committed
536
def compute_strides(shape, layout):
537
538
    """
    Computes strides assuming no padding exists
Martin Bauer's avatar
Martin Bauer committed
539
540
541
542
543
544
545

    Args:
        shape: shape (size) of array
        layout: layout specification as tuple

    Returns:
        strides in elements, not in bytes
546
    """
Martin Bauer's avatar
Martin Bauer committed
547
548
549
550
    dim = len(shape)
    assert len(layout) == dim
    assert len(set(layout)) == dim
    strides = [0] * dim
551
    product = 1
552
    for j in reversed(layout):
553
554
555
        strides[j] = product
        product *= shape[j]
    return tuple(strides)
Martin Bauer's avatar
Martin Bauer committed
556
557


Martin Bauer's avatar
Martin Bauer committed
558
559
560
def offset_component_to_direction_string(coordinate_id: int, value: int) -> str:
    """Translates numerical offset to string notation.

Martin Bauer's avatar
Martin Bauer committed
561
562
563
564
565
    x offsets are labeled with east 'E' and 'W',
    y offsets with north 'N' and 'S' and
    z offsets with top 'T' and bottom 'B'
    If the absolute value of the offset is bigger than 1, this number is prefixed.

Martin Bauer's avatar
Martin Bauer committed
566
567
568
569
570
571
572
573
574
    Args:
        coordinate_id: integer 0, 1 or 2 standing for x,y and z
        value: integer offset

    Examples:
        >>> offset_component_to_direction_string(0, 1)
        'E'
        >>> offset_component_to_direction_string(1, 2)
        '2N'
Martin Bauer's avatar
Martin Bauer committed
575
    """
Martin Bauer's avatar
Martin Bauer committed
576
577
    name_components = (('W', 'E'),  # west, east
                       ('S', 'N'),  # south, north
578
                       ('B', 'T'))  # bottom, top
Martin Bauer's avatar
Martin Bauer committed
579
580
581
    if value == 0:
        result = ""
    elif value < 0:
Martin Bauer's avatar
Martin Bauer committed
582
        result = name_components[coordinate_id][0]
Martin Bauer's avatar
Martin Bauer committed
583
    else:
Martin Bauer's avatar
Martin Bauer committed
584
        result = name_components[coordinate_id][1]
Martin Bauer's avatar
Martin Bauer committed
585
586
587
588
589
    if abs(value) > 1:
        result = "%d%s" % (abs(value), result)
    return result


Martin Bauer's avatar
Martin Bauer committed
590
def offset_to_direction_string(offsets: Sequence[int]) -> str:
Martin Bauer's avatar
Martin Bauer committed
591
592
    """
    Translates numerical offset to string notation.
Martin Bauer's avatar
Martin Bauer committed
593
594
595
596
597
598
599
600
601
    For details see :func:`offset_component_to_direction_string`
    Args:
        offsets: 3-tuple with x,y,z offset

    Examples:
        >>> offset_to_direction_string([1, -1, 0])
        'SE'
        >>> offset_to_direction_string(([-3, 0, -2]))
        '2B3W'
Martin Bauer's avatar
Martin Bauer committed
602
603
    """
    names = ["", "", ""]
Martin Bauer's avatar
Martin Bauer committed
604
605
    for i in range(len(offsets)):
        names[i] = offset_component_to_direction_string(i, offsets[i])
Martin Bauer's avatar
Martin Bauer committed
606
607
608
609
610
611
    name = "".join(reversed(names))
    if name == "":
        name = "C"
    return name


Martin Bauer's avatar
Martin Bauer committed
612
def direction_string_to_offset(direction: str, dim: int = 3):
Martin Bauer's avatar
Martin Bauer committed
613
    """
Martin Bauer's avatar
Martin Bauer committed
614
    Reverse mapping of :func:`offset_to_direction_string`
Martin Bauer's avatar
Martin Bauer committed
615
616
617
618
619
620
621
622
623
624
625
626

    Args:
        direction: string representation of offset
        dim: dimension of offset, i.e the length of the returned list

    Examples:
        >>> direction_string_to_offset('NW', dim=3)
        array([-1,  1,  0])
        >>> direction_string_to_offset('NW', dim=2)
        array([-1,  1])
        >>> direction_string_to_offset(offset_to_direction_string((3,-2,1)))
        array([ 3, -2,  1])
Martin Bauer's avatar
Martin Bauer committed
627
    """
Martin Bauer's avatar
Martin Bauer committed
628
    offset_dict = {
Martin Bauer's avatar
Martin Bauer committed
629
630
631
632
633
634
635
636
637
638
639
640
641
        'C': np.array([0, 0, 0]),

        'W': np.array([-1, 0, 0]),
        'E': np.array([1, 0, 0]),

        'S': np.array([0, -1, 0]),
        'N': np.array([0, 1, 0]),

        'B': np.array([0, 0, -1]),
        'T': np.array([0, 0, 1]),
    }
    offset = np.array([0, 0, 0])

Martin Bauer's avatar
Martin Bauer committed
642
    while len(direction) > 0:
Martin Bauer's avatar
Martin Bauer committed
643
        factor = 1
Martin Bauer's avatar
Martin Bauer committed
644
645
646
647
648
649
650
651
652
        first_non_digit = 0
        while direction[first_non_digit].isdigit():
            first_non_digit += 1
        if first_non_digit > 0:
            factor = int(direction[:first_non_digit])
            direction = direction[first_non_digit:]
        cur_offset = offset_dict[direction[0]]
        offset += factor * cur_offset
        direction = direction[1:]
Martin Bauer's avatar
Martin Bauer committed
653
    return offset[:dim]