field.py 33.7 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, Set
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

Martin Bauer's avatar
Martin Bauer committed
12
13
__all__ = ['Field', 'fields', 'FieldType']

14

15
16
17
18
def fields(description=None, index_dimensions=0, layout=None, **kwargs):
    """Creates pystencils fields from a string description.

    Examples:
Martin Bauer's avatar
Martin Bauer committed
19
20
21
22
        Create a 2D scalar and vector field:
            >>> s, v = fields("s, v(2): double[2D]")
            >>> assert s.spatial_dimensions == 2 and s.index_dimensions == 0
            >>> assert (v.spatial_dimensions, v.index_dimensions, v.index_shape) == (2, 1, (2,))
23

Martin Bauer's avatar
Martin Bauer committed
24
25
26
27
        Create an integer field of shape (10, 20):
            >>> f = fields("f : int32[10, 20]")
            >>> f.has_fixed_shape, f.shape
            (True, (10, 20))
28

Martin Bauer's avatar
Martin Bauer committed
29
30
31
32
33
        Numpy arrays can be used as template for shape and data type of field:
            >>> arr_s, arr_v = np.zeros([20, 20]), np.zeros([20, 20, 2])
            >>> s, v = fields("s, v(2)", s=arr_s, v=arr_v)
            >>> assert s.index_dimensions == 0 and s.dtype.numpy_dtype == arr_s.dtype
            >>> assert v.index_shape == (2,)
34
35


Martin Bauer's avatar
Martin Bauer committed
36
37
38
39
40
41
42
43
44
45
        Format string can be left out, field names are taken from keyword arguments.
            >>> fields(f1=arr_s, f2=arr_s)
            [f1, f2]

        The keyword names ``index_dimension`` and ``layout`` have special meaning, don't use them for field names
            >>> f = fields(f=arr_v, index_dimensions=1)
            >>> assert f.index_dimensions == 1
            >>> f = fields("pdfs(19) : float32[3D]", layout='fzyx')
            >>> f.layout
            (2, 1, 0)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    """
    result = []
    if description:
        field_descriptions, dtype, shape = _parse_description(description)
        layout = 'numpy' if layout is None else layout
        for field_name, idx_shape in field_descriptions:
            if field_name in kwargs:
                arr = kwargs[field_name]
                idx_shape_of_arr = () if not len(idx_shape) else arr.shape[-len(idx_shape):]
                assert idx_shape_of_arr == idx_shape
                f = Field.create_from_numpy_array(field_name, kwargs[field_name], index_dimensions=len(idx_shape))
            elif isinstance(shape, tuple):
                f = Field.create_fixed_size(field_name, shape + idx_shape, dtype=dtype,
                                            index_dimensions=len(idx_shape), layout=layout)
            elif isinstance(shape, int):
                f = Field.create_generic(field_name, spatial_dimensions=shape, dtype=dtype,
                                         index_shape=idx_shape, layout=layout)
            elif shape is None:
                f = Field.create_generic(field_name, spatial_dimensions=2, dtype=dtype,
                                         index_shape=idx_shape, layout=layout)
            else:
                assert False
            result.append(f)
    else:
        assert layout is None, "Layout can not be specified when creating Field from numpy array"
        for field_name, arr in kwargs.items():
            result.append(Field.create_from_numpy_array(field_name, arr, index_dimensions=index_dimensions))

    if len(result) == 0:
        return None
    elif len(result) == 1:
        return result[0]
    else:
        return result


82
83
84
85
86
87
88
89
90
91
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
92
    def is_generic(field):
93
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
94
        return field.field_type == FieldType.GENERIC
95
96

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
97
    def is_indexed(field):
98
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
99
        return field.field_type == FieldType.INDEXED
100
101

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
102
    def is_buffer(field):
103
        assert isinstance(field, Field)
Martin Bauer's avatar
Martin Bauer committed
104
        return field.field_type == FieldType.BUFFER
105
106


107
class Field:
108
109
110
111
    """
    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
112
    Creating Fields:
Martin Bauer's avatar
Martin Bauer committed
113
114
        The preferred method to create fields is the `fields` function.
        Alternatively one can use one of the static functions `Field.create_generic`, `Field.create_from_numpy_array`
115
        and `Field.create_fixed_size`. Don't instantiate the Field directly!
Martin Bauer's avatar
Martin Bauer committed
116
117
118
119
120
        Fields can be created with known or unknown shapes:

        1. If you want to create a kernel with fixed loop sizes i.e. the shape of the array is already known.
           This is usually the case if just-in-time compilation directly from Python is done.
           (see `Field.create_from_numpy_array`
121
        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
122
           beforehand for a library. (see `Field.create_generic`)
123

Martin Bauer's avatar
Martin Bauer committed
124
    Dimensions and Indexing:
125
126
        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
127
        looped over. Additionally N values are stored per cell. In this case spatial_dimensions is two or three,
Martin Bauer's avatar
Martin Bauer committed
128
        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
129
        are four dimensions, two spatial and two index dimensions: ``len(arr.shape) == spatial_dims + index_dims``
130

Martin Bauer's avatar
Martin Bauer committed
131
132
133
134
135
        The shape of the index dimension does not have to be specified. Just use the 'index_dimensions' parameter.
        However, it is good practice to define the shape, since out of bounds accesses can be directly detected in this
        case. The shape can be passed with the 'index_shape' parameter of the field creation functions.

        When accessing (indexing) a field the result is a `Field.Access` which is derived from sympy Symbol.
Martin Bauer's avatar
Martin Bauer committed
136
        First specify the spatial offsets in [], then in case index_dimension>0 the indices in ()
Martin Bauer's avatar
Martin Bauer committed
137
        e.g. ``f[-1,0,0](7)``
138

Martin Bauer's avatar
Martin Bauer committed
139
    Example using no index dimensions:
140
        >>> a = np.zeros([10, 10])
Martin Bauer's avatar
Martin Bauer committed
141
        >>> f = Field.create_from_numpy_array("f", a, index_dimensions=0)
Martin Bauer's avatar
Martin Bauer committed
142
        >>> jacobi = (f[-1,0] + f[1,0] + f[0,-1] + f[0,1]) / 4
143

Martin Bauer's avatar
Martin Bauer committed
144
    Examples for index dimensions to create LB field and implement stream pull:
Martin Bauer's avatar
Martin Bauer committed
145
        >>> from pystencils import Assignment
146
        >>> stencil = np.array([[0,0], [0,1], [0,-1]])
Martin Bauer's avatar
Martin Bauer committed
147
        >>> src, dst = fields("src(3), dst(3) : double[2D]")
148
        >>> for i, offset in enumerate(stencil):
149
150
151
152
        ...     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)
153
    """
154
155

    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
156
157
    def create_generic(field_name, spatial_dimensions, dtype=np.float64, index_dimensions=0, layout='numpy',
                       index_shape=None, field_type=FieldType.GENERIC) -> 'Field':
158
159
160
        """
        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
161
162
163
164
165
166
167
        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
168
                    over dimension 0. Also allowed: the strings 'numpy' (0,1,..d) or 'reverse_numpy' (d, ..., 1, 0)
Martin Bauer's avatar
Martin Bauer committed
169
170
171
172
173
            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
174
        """
175
176
177
        if index_shape is not None:
            assert index_dimensions == 0 or index_dimensions == len(index_shape)
            index_dimensions = len(index_shape)
178
        if isinstance(layout, str):
Martin Bauer's avatar
Martin Bauer committed
179
180
181
182
183
184
            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)])
185
        else:
Martin Bauer's avatar
Martin Bauer committed
186
            shape = tuple([shape_symbol[i] for i in range(spatial_dimensions)] + list(index_shape))
187

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

Martin Bauer's avatar
Martin Bauer committed
190
191
192
        np_data_type = np.dtype(dtype)
        if np_data_type.fields is not None:
            if index_dimensions != 0:
193
194
195
196
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

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

199
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
200
201
202
    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.

203
        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
204
205
206
207
208

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

Martin Bauer's avatar
Martin Bauer committed
214
215
216
        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
217

Martin Bauer's avatar
Martin Bauer committed
218
219
        strides = tuple([s // np.dtype(array.dtype).itemsize for s in array.strides])
        shape = tuple(int(s) for s in array.shape)
220

Martin Bauer's avatar
Martin Bauer committed
221
222
223
        numpy_dtype = np.dtype(array.dtype)
        if numpy_dtype.fields is not None:
            if index_dimensions != 0:
224
225
226
227
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

Martin Bauer's avatar
Martin Bauer committed
228
        return Field(field_name, FieldType.GENERIC, array.dtype, spatial_layout, shape, strides)
229
230

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

Martin Bauer's avatar
Martin Bauer committed
236
237
238
239
240
241
242
        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)
243
        """
Martin Bauer's avatar
Martin Bauer committed
244
245
        spatial_dimensions = len(shape) - index_dimensions
        assert spatial_dimensions >= 1
246

247
        if isinstance(layout, str):
Martin Bauer's avatar
Martin Bauer committed
248
            layout = layout_string_to_tuple(layout, spatial_dimensions + index_dimensions)
249
250

        shape = tuple(int(s) for s in shape)
251
        if strides is None:
Martin Bauer's avatar
Martin Bauer committed
252
            strides = compute_strides(shape, layout)
253
254
255
        else:
            assert len(strides) == len(shape)
            strides = tuple([s // np.dtype(dtype).itemsize for s in strides])
256

Martin Bauer's avatar
Martin Bauer committed
257
258
259
        numpy_dtype = np.dtype(dtype)
        if numpy_dtype.fields is not None:
            if index_dimensions != 0:
260
261
262
263
                raise ValueError("Structured arrays/fields are not allowed to have an index dimension")
            shape += (1,)
            strides += (1,)

Martin Bauer's avatar
Martin Bauer committed
264
265
266
267
        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)
268

Martin Bauer's avatar
Martin Bauer committed
269
    def __init__(self, field_name, field_type, dtype, layout, shape, strides):
270
        """Do not use directly. Use static create* methods"""
271
        self._field_name = field_name
Martin Bauer's avatar
Martin Bauer committed
272
        assert isinstance(field_type, FieldType)
273
        assert len(shape) == len(strides)
Martin Bauer's avatar
Martin Bauer committed
274
        self.field_type = field_type
Martin Bauer's avatar
Martin Bauer committed
275
        self._dtype = create_type(dtype)
Martin Bauer's avatar
Martin Bauer committed
276
        self._layout = normalize_layout(layout)
277
278
        self.shape = shape
        self.strides = strides
279
        self.latex_name = None  # type: Optional[str]
280

Martin Bauer's avatar
Martin Bauer committed
281
    def new_field_with_different_name(self, new_name):
Martin Bauer's avatar
Martin Bauer committed
282
        return Field(new_name, self.field_type, self._dtype, self._layout, self.shape, self.strides)
283

284
    @property
Martin Bauer's avatar
Martin Bauer committed
285
    def spatial_dimensions(self) -> int:
286
287
288
        return len(self._layout)

    @property
Martin Bauer's avatar
Martin Bauer committed
289
    def index_dimensions(self) -> int:
290
        return len(self.shape) - len(self._layout)
291
292
293
294
295
296

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

    @property
Martin Bauer's avatar
Martin Bauer committed
297
    def name(self) -> str:
298
        return self._field_name
299
300

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

304
    @property
Martin Bauer's avatar
Martin Bauer committed
305
    def has_fixed_shape(self):
Martin Bauer's avatar
Martin Bauer committed
306
        return is_integer_sequence(self.shape)
307

308
    @property
Martin Bauer's avatar
Martin Bauer committed
309
310
    def index_shape(self):
        return self.shape[self.spatial_dimensions:]
311

312
    @property
Martin Bauer's avatar
Martin Bauer committed
313
314
    def has_fixed_index_shape(self):
        return is_integer_sequence(self.index_shape)
315

316
    @property
Martin Bauer's avatar
Martin Bauer committed
317
318
    def spatial_strides(self):
        return self.strides[:self.spatial_dimensions]
319
320

    @property
Martin Bauer's avatar
Martin Bauer committed
321
322
    def index_strides(self):
        return self.strides[self.spatial_dimensions:]
323
324
325
326
327
328

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

    def __repr__(self):
329
        return self._field_name
330

Martin Bauer's avatar
Martin Bauer committed
331
332
333
334
    def neighbor(self, coord_id, offset):
        offset_list = [0] * self.spatial_dimensions
        offset_list[coord_id] = offset
        return Field.Access(self, tuple(offset_list))
335

336
    def neighbors(self, stencil):
337
        return [self.__getitem__(s) for s in stencil]
338

339
    @property
Martin Bauer's avatar
Martin Bauer committed
340
341
342
    def center_vector(self):
        index_shape = self.index_shape
        if len(index_shape) == 0:
343
            return self.center
Martin Bauer's avatar
Martin Bauer committed
344
345
346
        elif len(index_shape) == 1:
            return sp.Matrix([self(i) for i in range(index_shape[0])])
        elif len(index_shape) == 2:
347
348
349
            def cb(*args):
                r = self.__call__(*args)
                return r
Martin Bauer's avatar
Martin Bauer committed
350
            return sp.Matrix(*index_shape, cb)
351

352
    @property
353
    def center(self):
Martin Bauer's avatar
Martin Bauer committed
354
        center = tuple([0] * self.spatial_dimensions)
355
356
        return Field.Access(self, center)

357
358
359
360
    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
361
            offset = tuple(direction_string_to_offset(offset, self.spatial_dimensions))
362
363
        if type(offset) is not tuple:
            offset = (offset,)
Martin Bauer's avatar
Martin Bauer committed
364
        if len(offset) != self.spatial_dimensions:
365
            raise ValueError("Wrong number of spatial indices: "
Martin Bauer's avatar
Martin Bauer committed
366
                             "Got %d, expected %d" % (len(offset), self.spatial_dimensions))
367
368
        return Field.Access(self, offset)

Martin Bauer's avatar
Martin Bauer committed
369
370
371
    def absolute_access(self, offset, index):
        return Field.Access(self, offset, index, is_absolute_access=True)

372
    def __call__(self, *args, **kwargs):
Martin Bauer's avatar
Martin Bauer committed
373
        center = tuple([0] * self.spatial_dimensions)
374
375
376
        return Field.Access(self, center)(*args, **kwargs)

    def __hash__(self):
377
        return hash((self._layout, self.shape, self.strides, self._dtype, self.field_type, self._field_name))
378
379

    def __eq__(self, other):
Martin Bauer's avatar
Martin Bauer committed
380
381
        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
382
        return self_tuple == other_tuple
383

384
385
386
    PREFIX = "f"
    STRIDE_PREFIX = PREFIX + "stride_"
    SHAPE_PREFIX = PREFIX + "shape_"
Martin Bauer's avatar
Martin Bauer committed
387
388
    STRIDE_DTYPE = create_composite_type_from_string("const int *")
    SHAPE_DTYPE = create_composite_type_from_string("const int *")
389
    DATA_PREFIX = PREFIX + "d_"
390

Martin Bauer's avatar
Martin Bauer committed
391
    # noinspection PyAttributeOutsideInit,PyUnresolvedReferences
392
    class Access(sp.Symbol):
Martin Bauer's avatar
Martin Bauer committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        """Class representing a relative access into a `Field`.

        This class behaves like a normal sympy Symbol, it is actually derived from it. One can built up
        sympy expressions using field accesses, solve for them, etc.

        Examples:
            >>> vector_field_2d = fields("v(2): double[2D]")  # create a 2D vector field
            >>> northern_neighbor_y_component = vector_field_2d[0, 1](1)
            >>> northern_neighbor_y_component
            v_N^1
            >>> central_y_component = vector_field_2d(1)
            >>> central_y_component
            v_C^1
            >>> central_y_component.get_shifted(1, 0)  # move the existing access
            v_E^1
            >>> central_y_component.at_index(0)  # change component
            v_C^0
        """
411
412
413
414
        def __new__(cls, name, *args, **kwargs):
            obj = Field.Access.__xnew_cached_(cls, name, *args, **kwargs)
            return obj

Martin Bauer's avatar
Martin Bauer committed
415
        def __new_stage2__(self, field, offsets=(0, 0, 0), idx=None, is_absolute_access=False):
Martin Bauer's avatar
Martin Bauer committed
416
417
418
            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])
419
420

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

Martin Bauer's avatar
Martin Bauer committed
423
424
425
            if constant_offsets:
                offset_name = offset_to_direction_string(offsets)
                if field.index_dimensions == 0:
426
                    superscript = None
Martin Bauer's avatar
Martin Bauer committed
427
                elif field.index_dimensions == 1:
428
                    superscript = str(idx[0])
429
                else:
Martin Bauer's avatar
Martin Bauer committed
430
431
432
433
                    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):
434
435
                        if i >= bound:
                            raise ValueError("Field index out of bounds")
436
            else:
Martin Bauer's avatar
Martin Bauer committed
437
                offset_name = "%0.10X" % (abs(hash(tuple(offsets_and_index))))
438
                superscript = None
439

Martin Bauer's avatar
Martin Bauer committed
440
            symbol_name = "%s_%s" % (field_name, offset_name)
441
            if superscript is not None:
Martin Bauer's avatar
Martin Bauer committed
442
                symbol_name += "^" + superscript
443

Martin Bauer's avatar
Martin Bauer committed
444
            obj = super(Field.Access, self).__xnew__(self, symbol_name)
445
446
447
448
449
450
451
            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
452
            obj._offsetName = offset_name
453
            obj._superscript = superscript
454
455
            obj._index = idx

Martin Bauer's avatar
Martin Bauer committed
456
457
458
459
460
461
            obj._indirect_addressing_fields = set()
            for e in chain(obj._offsets, obj._index):
                if isinstance(e, sp.Basic):
                    obj._indirect_addressing_fields.update(a.field for a in e.atoms(Field.Access))

            obj._is_absolute_access = is_absolute_access
462
463
            return obj

464
        def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
465
            return self.field, self.offsets, self.index, self.is_absolute_access
466

Martin Bauer's avatar
Martin Bauer committed
467
        # noinspection SpellCheckingInspection
468
        __xnew__ = staticmethod(__new_stage2__)
Martin Bauer's avatar
Martin Bauer committed
469
        # noinspection SpellCheckingInspection
470
471
472
        __xnew_cached_ = staticmethod(cacheit(__new_stage2__))

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

            idx = tuple(idx)
477

Martin Bauer's avatar
Martin Bauer committed
478
            if self.field.index_dimensions == 0 and idx == (0,):
479
480
                idx = ()

Martin Bauer's avatar
Martin Bauer committed
481
            if len(idx) != self.field.index_dimensions:
482
                raise ValueError("Wrong number of indices: "
Martin Bauer's avatar
Martin Bauer committed
483
                                 "Got %d, expected %d" % (len(idx), self.field.index_dimensions))
484
485
            return Field.Access(self.field, self._offsets, idx)

Martin Bauer's avatar
Martin Bauer committed
486
487
488
        def __getitem__(self, *idx):
            return self.__call__(*idx)

Martin Bauer's avatar
Martin Bauer committed
489
490
491
492
493
        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")

494
        @property
Martin Bauer's avatar
Martin Bauer committed
495
496
        def field(self) -> 'Field':
            """Field that the Access points to"""
497
498
499
            return self._field

        @property
Martin Bauer's avatar
Martin Bauer committed
500
501
        def offsets(self) -> Tuple:
            """Spatial offset as tuple"""
502
            return tuple(self._offsets)
503

504
        @property
Martin Bauer's avatar
Martin Bauer committed
505
506
        def required_ghost_layers(self) -> int:
            """Largest spatial distance that is accessed."""
507
508
509
            return int(np.max(np.abs(self._offsets)))

        @property
Martin Bauer's avatar
Martin Bauer committed
510
        def nr_of_coordinates(self):
511
512
513
            return len(self._offsets)

        @property
Martin Bauer's avatar
Martin Bauer committed
514
        def offset_name(self) -> str:
Martin Bauer's avatar
Martin Bauer committed
515
516
517
518
519
520
521
            """Spatial offset as string, East-West for x, North-South for y and Top-Bottom for z coordinate.

            Example:
                >>> f = fields("f: double[2D]")
                >>> f[1, 1].offset_name  # north-east
                'NE'
            """
522
523
524
525
            return self._offsetName

        @property
        def index(self):
Martin Bauer's avatar
Martin Bauer committed
526
            """Value of index coordinates as tuple."""
527
528
            return self._index

Martin Bauer's avatar
Martin Bauer committed
529
        def neighbor(self, coord_id: int, offset: Sequence[int]) -> 'Field.Access':
Martin Bauer's avatar
Martin Bauer committed
530
531
532
533
534
535
536
537
538
539
540
            """Returns a new Access with changed spatial coordinates.

            Args:
                coord_id: index of the coordinate to change (0 for x, 1 for y,...)
                offset: incremental change of this coordinate

            Example:
                >>> f = fields('f: [2D]')
                >>> f[0,0].neighbor(coord_id=1, offset=-1)
                f_S
            """
Martin Bauer's avatar
Martin Bauer committed
541
542
543
            offset_list = list(self.offsets)
            offset_list[coord_id] += offset
            return Field.Access(self.field, tuple(offset_list), self.index)
544

Martin Bauer's avatar
Martin Bauer committed
545
        def get_shifted(self, *shift)-> 'Field.Access':
Martin Bauer's avatar
Martin Bauer committed
546
547
548
549
550
551
552
            """Returns a new Access with changed spatial coordinates

            Example:
                >>> f = fields("f: [2D]")
                >>> f[0,0].get_shifted(1, 1)
                f_NE
            """
553
554
            return Field.Access(self.field, tuple(a + b for a, b in zip(shift, self.offsets)), self.index)

Martin Bauer's avatar
Martin Bauer committed
555
556
557
558
559
560
561
562
        def at_index(self, *idx_tuple) -> 'Field.Access':
            """Returns new Access with changed index.

            Example:
                >>> f = fields("f(9): [2D]")
                >>> f(0).at_index(8)
                f_C^8
            """
563
564
            return Field.Access(self.field, self.offsets, idx_tuple)

Martin Bauer's avatar
Martin Bauer committed
565
566
567
568
569
570
571
572
573
574
575
576
577
        @property
        def is_absolute_access(self) -> bool:
            """Indicates if a field access is relative to the loop counters (this is the default) or absolute"""
            return self._is_absolute_access

        @property
        def indirect_addressing_fields(self) -> Set['Field']:
            """Returns a set of fields that the access depends on.

             e.g. f[index_field[1, 0]], the outer access to f depends on index_field
             """
            return self._indirect_addressing_fields

578
        def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
579
580
            super_class_contents = list(super(Field.Access, self)._hashable_content())
            t = tuple(super_class_contents + [hash(self._field), self._index] + self._offsets)
581
            return t
Martin Bauer's avatar
Martin Bauer committed
582

Martin Bauer's avatar
Martin Bauer committed
583
        def _latex(self, _):
584
            n = self._field.latex_name if self._field.latex_name else self._field.name
Martin Bauer's avatar
Martin Bauer committed
585
586
587
588
            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
589
590


Martin Bauer's avatar
Martin Bauer committed
591
592
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
593
    coordinates = list(range(len(strides)))
Martin Bauer's avatar
Martin Bauer committed
594
    relevant_strides = [stride for i, stride in enumerate(strides) if i not in index_dimension_ids]
595
    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
596
    return normalize_layout(result)
597
598


Martin Bauer's avatar
Martin Bauer committed
599
600
601
602
603
604
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
605
606
607
608
609

    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
610

Martin Bauer's avatar
Martin Bauer committed
611
    The index_dimension_ids parameter leaves specifies which coordinates should not be
Martin Bauer's avatar
Martin Bauer committed
612
    """
Martin Bauer's avatar
Martin Bauer committed
613
614
    index_dimension_ids = [] if index_dimension_ids is None else index_dimension_ids
    return get_layout_from_strides(arr.strides, index_dimension_ids)
615
616


Martin Bauer's avatar
Martin Bauer committed
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
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)
633
634
    """
    assert set(layout) == set(range(len(shape))), "Wrong layout descriptor"
Martin Bauer's avatar
Martin Bauer committed
635
    cur_layout = list(range(len(shape)))
636
637
    swaps = []
    for i in range(len(layout)):
Martin Bauer's avatar
Martin Bauer committed
638
639
640
641
642
        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)
643
644
645
646
647

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

648
649
650
651
652
    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
653
        res = aligned_empty(shape, alignment, byte_offset=byte_offset, **kwargs)
654

655
656
657
658
659
    for a, b in reversed(swaps):
        res = res.swapaxes(a, b)
    return res


Martin Bauer's avatar
Martin Bauer committed
660
661
def spatial_layout_string_to_tuple(layout_str: str, dim: int) -> Tuple[int, ...]:
    if layout_str in ('fzyx', 'zyxf'):
662
663
        assert dim <= 3
        return tuple(reversed(range(dim)))
664

Martin Bauer's avatar
Martin Bauer committed
665
    if layout_str in ('fzyx', 'f', 'reverse_numpy', 'SoA'):
666
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
667
    elif layout_str in ('c', 'numpy', 'AoS'):
668
        return tuple(range(dim))
Martin Bauer's avatar
Martin Bauer committed
669
    raise ValueError("Unknown layout descriptor " + layout_str)
670
671


Martin Bauer's avatar
Martin Bauer committed
672
673
674
def layout_string_to_tuple(layout_str, dim):
    layout_str = layout_str.lower()
    if layout_str == 'fzyx' or layout_str == 'soa':
675
676
        assert dim <= 4
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
677
    elif layout_str == 'zyxf' or layout_str == 'aos':
678
        assert dim <= 4
Martin Bauer's avatar
Martin Bauer committed
679
        return tuple(reversed(range(dim - 1))) + (dim - 1,)
Martin Bauer's avatar
Martin Bauer committed
680
    elif layout_str == 'f' or layout_str == 'reverse_numpy':
681
        return tuple(reversed(range(dim)))
Martin Bauer's avatar
Martin Bauer committed
682
    elif layout_str == 'c' or layout_str == 'numpy':
683
        return tuple(range(dim))
Martin Bauer's avatar
Martin Bauer committed
684
    raise ValueError("Unknown layout descriptor " + layout_str)
685
686


Martin Bauer's avatar
Martin Bauer committed
687
def normalize_layout(layout):
688
    """Takes a layout tuple and subtracts the minimum from all entries"""
Martin Bauer's avatar
Martin Bauer committed
689
690
    min_entry = min(layout)
    return tuple(i - min_entry for i in layout)
691
692


Martin Bauer's avatar
Martin Bauer committed
693
def compute_strides(shape, layout):
694
695
    """
    Computes strides assuming no padding exists
Martin Bauer's avatar
Martin Bauer committed
696
697
698
699
700
701
702

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

    Returns:
        strides in elements, not in bytes
703
    """
Martin Bauer's avatar
Martin Bauer committed
704
705
706
707
    dim = len(shape)
    assert len(layout) == dim
    assert len(set(layout)) == dim
    strides = [0] * dim
708
    product = 1
709
    for j in reversed(layout):
710
711
712
        strides[j] = product
        product *= shape[j]
    return tuple(strides)
Martin Bauer's avatar
Martin Bauer committed
713
714


Martin Bauer's avatar
Martin Bauer committed
715
716
717
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
718
719
720
721
722
    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
723
724
725
726
727
728
729
730
731
    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
732
    """
733
    assert 0 <= coordinate_id < 3, "Works only for at most 3D arrays"
Martin Bauer's avatar
Martin Bauer committed
734
735
    name_components = (('W', 'E'),  # west, east
                       ('S', 'N'),  # south, north
736
                       ('B', 'T'))  # bottom, top
Martin Bauer's avatar
Martin Bauer committed
737
738
739
    if value == 0:
        result = ""
    elif value < 0:
Martin Bauer's avatar
Martin Bauer committed
740
        result = name_components[coordinate_id][0]
Martin Bauer's avatar
Martin Bauer committed
741
    else:
Martin Bauer's avatar
Martin Bauer committed
742
        result = name_components[coordinate_id][1]
Martin Bauer's avatar
Martin Bauer committed
743
744
745
746
747
    if abs(value) > 1:
        result = "%d%s" % (abs(value), result)
    return result


Martin Bauer's avatar
Martin Bauer committed
748
def offset_to_direction_string(offsets: Sequence[int]) -> str:
Martin Bauer's avatar
Martin Bauer committed
749
750
    """
    Translates numerical offset to string notation.
Martin Bauer's avatar
Martin Bauer committed
751
752
753
754
755
756
757
758
759
    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
760
    """
761
762
    if len(offsets) > 3:
        return str(offsets)
Martin Bauer's avatar
Martin Bauer committed
763
    names = ["", "", ""]
Martin Bauer's avatar
Martin Bauer committed
764
765
    for i in range(len(offsets)):
        names[i] = offset_component_to_direction_string(i, offsets[i])
Martin Bauer's avatar
Martin Bauer committed
766
767
768
769
770
771
    name = "".join(reversed(names))
    if name == "":
        name = "C"
    return name


Martin Bauer's avatar
Martin Bauer committed
772
def direction_string_to_offset(direction: str, dim: int = 3):
Martin Bauer's avatar
Martin Bauer committed
773
    """
Martin Bauer's avatar
Martin Bauer committed
774
    Reverse mapping of :func:`offset_to_direction_string`
Martin Bauer's avatar
Martin Bauer committed
775
776
777
778
779
780
781
782
783
784
785
786

    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
787
    """
Martin Bauer's avatar
Martin Bauer committed
788
    offset_dict = {
Martin Bauer's avatar
Martin Bauer committed
789
790
791
792
793
794
795
796
797
798
799
800
801
        '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
802
    while len(direction) > 0:
Martin Bauer's avatar
Martin Bauer committed
803
        factor = 1
Martin Bauer's avatar
Martin Bauer committed
804
805
806
807
808
809
810
811
812
        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
813
    return offset[:dim]
814

Martin Bauer's avatar
Martin Bauer committed
815

816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
def _parse_type_description(type_description):
    if not type_description:
        return np.float64, None
    elif '[' in type_description:
        assert type_description[-1] == ']'
        type_part, size_part = type_description[:-1].split("[", )
        if not type_part:
            type_part = "float64"
        if size_part.lower()[-1] == 'd':
            size_part = int(size_part[:-1])
        else:
            size_part = tuple(int(i) for i in size_part.split(','))
    else:
        type_part, size_part = type_description, None

    dtype = np.dtype(type_part).type
    return dtype, size_part


def _parse_field_description(description):
    if '(' not in description:
        return description, ()
    assert description[-1] == ')'
    name, index_shape = description[:-1].split('(')
    index_shape = tuple(int(i) for i in index_shape.split(','))
    return name, index_shape


def _parse_description(description):
    description = description.replace(' ', '')
    if ':' in description:
        name_descr, type_descr = description.split(':')
    else:
        name_descr, type_descr = description, ''

    # correct ',' splits inside brackets
    field_names = name_descr.split(',')
    cleaned_field_names = []
    prefix = ''
    for field_name in field_names:
        full_field_name = prefix + field_name
        if '(' in full_field_name and ')' not in full_field_name:
            prefix += field_name + ','
        else:
            prefix = ''
            cleaned_field_names.append(full_field_name)

    dtype, size = _parse_type_description(type_descr)
    fields_info = tuple(_parse_field_description(fd) for fd in cleaned_field_names)
    return fields_info, dtype, size