/
basic.py
1593 lines (1261 loc) · 49.6 KB
/
basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
from collections import namedtuple
from ctypes import POINTER, _Pointer, c_char_p, c_char
from functools import reduce
from operator import mul
import numpy as np
import sympy
from sympy.core.assumptions import _assume_rules
from sympy.core.decorators import call_highest_priority
from cached_property import cached_property
from devito.data import default_allocator
from devito.parameters import configuration
from devito.tools import (Pickable, as_tuple, ctypes_to_cstr, dtype_to_ctype,
frozendict, memoized_meth, sympy_mutex)
from devito.types.args import ArgProvider
from devito.types.caching import Cached, Uncached
from devito.types.lazy import Evaluable
from devito.types.utils import DimensionTuple
__all__ = ['Symbol', 'Scalar', 'Indexed', 'IndexedData', 'DeviceMap']
Size = namedtuple('Size', 'left right')
Offset = namedtuple('Offset', 'left right')
class CodeSymbol(object):
"""
Abstract base class for objects representing symbols in the generated code.
The _C_* properties describe the object in C-land. For example its name and
its type.
The _mem_* properties describe the object memory allocation strategy. There
are three axes, with a few possible values each:
* "liveness": `_mem_external`, `_mem_internal_eager`, `_mem_internal_lazy`
* "space": `_mem_local`, `_mem_mapped`, `_mem_host`
* "scope": `_mem_stack`, `_mem_heap`, `_mem_global`, `_mem_shared`,
`_mem_constant`
For example, an object that is `<_mem_internal_lazy, _mem_local, _mem_heap>`
is allocated within the Operator entry point, on either the host or device
memory (but not both), and on the heap. Refer to the __doc__ of the single
_mem_* properties for more info. Obviously, not all triplets make sense
for a given architecture.
"""
@abc.abstractmethod
def __init__(self, *args, **kwargs):
return
@property
@abc.abstractmethod
def dtype(self):
"""
The data type of the object in the generated code, represented as a
Python class:
* `numpy.dtype`: basic data types. For example, `np.float64 -> double`.
* `ctypes`: composite objects (e.g., structs), foreign types.
"""
return
@abc.abstractproperty
def _C_name(self):
"""
The name of the object in the generated code.
Returns
-------
str
"""
return
@property
def _C_typedata(self):
"""
The type of the object in the generated code as a `str`.
"""
_type = self._C_ctype
while issubclass(_type, _Pointer):
_type = _type._type_
# `ctypes` treats C strings specially
if _type is c_char_p:
_type = c_char
return ctypes_to_cstr(_type)
@abc.abstractproperty
def _C_ctype(self):
"""
The type of the object in the generated code as a `ctypes` class.
"""
return
@property
def _C_symbol(self):
"""
The entry symbol. This may or may not coincide with the symbol used
to construct symbolic expressions.
Returns
-------
Basic
"""
return self
@property
def _mem_external(self):
"""
True if the associated data is allocated and freed in Python, False otherwise.
"""
return False
@property
def _mem_internal_eager(self):
"""
True if the associated data is allocated and freed inside the first
Callable in which the symbol appears as a free variable.
"""
return False
@property
def _mem_internal_lazy(self):
"""
True if the associated data is allocated and freed at the level of
the Operator entry point.
"""
return False
@property
def _mem_local(self):
"""
True if the associated data is allocated in the underlying platform's
local memory space, False otherwise.
The local memory space is:
* the host DRAM if platform=CPU
* the device DRAM if platform=GPU
"""
return False
@property
def _mem_mapped(self):
"""
True if the associated data is allocated in the underlying platform's
local memory space and subsequently mapped to the underlying platform's
remote memory space, False otherwise.
The local memory space is:
* the host DRAM if platform=CPU
* the device DRAM if platform=GPU
The remote memory space is:
* the host DRAM if platform=GPU
* the device DRAM if platform=CPU
"""
return False
@property
def _mem_host(self):
"""
True if the associated data is systematically allocated in the host DRAM.
"""
return False
@property
def _mem_stack(self):
"""
True if the associated data is allocated on the stack, False otherwise.
"""
return False
@property
def _mem_heap(self):
"""
True if the associated data is allocated on the heap, False otherwise.
"""
return False
@property
def _mem_global(self):
"""
True if the symbol is globally scoped, False otherwise.
"""
return self._mem_constant
@property
def _mem_constant(self):
"""
True if the associated data is allocated in global constant memory,
False otherwise. This is a special case of `_mem_global`.
"""
return False
@property
def _mem_shared(self):
"""
True if the associated data is allocated in so called shared memory,
False otherwise.
"""
return False
class Basic(CodeSymbol):
"""
Abstract base class for objects to construct symbolic expressions.
Four relevant types inherit from this class:
* AbstractSymbol: represents a scalar; may carry data; may be used
to build equations.
* AbstractFunction: represents a discrete R^n -> R function; may
carry data; may be used to build equations.
* AbstractTensor: represents a discrete 2nd order tensor or vector:
R^n -> R^(nd x nd) tensor (nd dimensions),
R^n -> R^nd vector (nd dimensions),
may carry data; may be used to build equations.
* AbstractObject: represents a generic object, for example a (pointer
to) data structure.
Basic
|
--------------------------------------------------------------
| | | |
AbstractSymbol AbstractFunction AbstractTensor AbstractObject
All these subtypes must implement a number of methods/properties to enable
code generation via the Devito compiler. These methods/properties are
easily recognizable as their name starts with _C_.
Notes
-----
The AbstractFunction sub-hierarchy is implemented in :mod:`dense.py`.
The AbstractTensor sub-hierarchy is implemented in :mod:`tensor.py`.
"""
# Top hierarchy
is_AbstractFunction = False
is_AbstractTensor = False
is_AbstractObject = False
# Symbolic objects created internally by Devito
is_Symbol = False
is_ArrayBasic = False
is_Array = False
is_PointerArray = False
is_ObjectArray = False
is_Bundle = False
is_Object = False
is_LocalObject = False
# Created by the user
is_Input = False
# Scalar symbolic objects created by the user
is_Dimension = False
is_Constant = False
# Tensor symbolic objects created by the user
is_DiscreteFunction = False
is_Function = False
is_TimeFunction = False
is_TempFunction = False
is_SparseTimeFunction = False
is_SparseFunction = False
# Time dependence
is_TimeDependent = False
# Some other properties
is_PerfKnob = False # Does it impact the Operator performance?
@property
def base(self):
return self
@property
def bound_symbols(self):
"""
Unlike SymPy, we systematically define `bound_symbols` on all of
the API and internal objects that may be used to construct an
Operator.
"""
return set()
class AbstractSymbol(sympy.Symbol, Basic, Pickable, Evaluable):
"""
Base class for scalar symbols.
The hierarchy is structured as follows
AbstractSymbol
|
-------------------------------------
| |
DataSymbol Symbol
| |
---------------- -------------------
| | | |
Constant DefaultDimension Scalar Dimension
<:mod:`dimension.py`>
All symbols can be used to build equations. However, while DataSymbol
carries data, Symbol is a pure symbolic object.
Constant, DefaultDimension, and Dimension (and most of its subclasses) are
part of the user API; Scalar, instead, is only used internally by Devito.
DefaultDimension and Dimension define a problem dimension (in other words,
an "iteration space"). They can be used to index into Functions. For more
information, refer to :mod:`dimension.py`.
"""
is_AbstractSymbol = True
is_Symbol = True
# SymPy default assumptions
is_real = True
is_imaginary = False
is_commutative = True
__rkwargs__ = ('name', 'dtype', 'is_const')
@classmethod
def _filter_assumptions(cls, **kwargs):
"""Extract sympy.Symbol-specific kwargs."""
assumptions = {}
# pop predefined assumptions
for key in ('real', 'imaginary', 'commutative'):
kwargs.pop(key, None)
# extract sympy.Symbol-specific kwargs
for i in list(kwargs):
if i in _assume_rules.defined_facts:
assumptions[i] = kwargs.pop(i)
return assumptions, kwargs
def __new__(cls, *args, **kwargs):
name = kwargs.get('name') or args[0]
assumptions, kwargs = cls._filter_assumptions(**kwargs)
# Create the new Symbol
# Note: use __xnew__ to bypass sympy caching
newobj = sympy.Symbol.__xnew__(cls, name, **assumptions)
# Initialization
newobj._dtype = cls.__dtype_setup__(**kwargs)
newobj.__init_finalize__(*args, **kwargs)
return newobj
@classmethod
def __dtype_setup__(cls, **kwargs):
"""Extract the object data type from ``kwargs``."""
return kwargs.get('dtype', np.int32)
def __init__(self, *args, **kwargs):
# no-op, the true init is performed by __init_finalize__
pass
def __init_finalize__(self, *args, **kwargs):
self._is_const = kwargs.get('is_const', False)
def __eq__(self, other):
return (type(self) is type(other) and
self.dtype is other.dtype and
self.is_const == other.is_const and
super().__eq__(other))
__hash__ = sympy.Symbol.__hash__
def _hashable_content(self):
return super()._hashable_content() + (self.dtype, self.is_const)
@property
def dtype(self):
return self._dtype
@property
def indices(self):
return ()
@property
def dimensions(self):
return self.indices
@property
def shape(self):
return ()
@property
def ndim(self):
return 0
@property
def symbolic_shape(self):
return ()
@property
def function(self):
return self
def _evaluate(self, **kwargs):
return self
def indexify(self, indices=None):
return self
@property
def is_const(self):
"""
True if the symbol value cannot be modified within an Operator (and thus
its value is provided by the user directly from Python-land), False otherwise.
"""
return self._is_const
@property
def _C_name(self):
return self.name
@property
def _C_ctype(self):
return dtype_to_ctype(self.dtype)
def _subs(self, old, new, **hints):
"""
This stub allows sympy.Basic.subs to operate on an expression
involving devito Scalars. Ordinarily the comparisons between
devito subclasses of sympy types are quite strict.
"""
try:
if old.name == self.name:
return new
except AttributeError:
pass
return self
# Pickling support
__reduce_ex__ = Pickable.__reduce_ex__
def __getnewargs_ex__(self):
args, kwargs = Pickable.__getnewargs_ex__(self)
kwargs.update(self.assumptions0)
return args, kwargs
class Symbol(AbstractSymbol, Cached):
"""
A scalar symbol, cached by both Devito and SymPy, which does not carry
any data.
Notes
-----
A Symbol may not be in the SymPy cache, but still be present in the
Devito cache. This is because SymPy caches operations, rather than
actual objects.
"""
@classmethod
def _cache_key(cls, *args, **kwargs):
args = list(args)
key = {}
# The base type is necessary, otherwise two objects such as
# `Scalar(name='s')` and `Dimension(name='s')` would have the same key
key['cls'] = cls
# The name is always present, and added as if it were an arg
key['name'] = kwargs.pop('name', None) or args.pop(0)
# From the args
key['args'] = tuple(args)
# From the kwargs
key.update(kwargs)
return frozendict(key)
def __new__(cls, *args, **kwargs):
assumptions, kwargs = cls._filter_assumptions(**kwargs)
key = cls._cache_key(*args, **{**assumptions, **kwargs})
obj = cls._cache_get(key)
if obj is not None:
return obj
# Not in cache. Create a new Symbol via sympy.Symbol
args = list(args)
name = kwargs.pop('name', None) or args.pop(0)
# Note: use __xnew__ to bypass sympy caching
newobj = sympy.Symbol.__xnew__(cls, name, **assumptions)
# Initialization
newobj._dtype = cls.__dtype_setup__(**kwargs)
newobj.__init_finalize__(name, *args, **kwargs)
# Store new instance in symbol cache
Cached.__init__(newobj, key)
return newobj
__hash__ = Cached.__hash__
class DataSymbol(AbstractSymbol, Uncached):
"""
A unique scalar symbol that carries data.
"""
def __new__(cls, *args, **kwargs):
# Create a new Symbol via sympy.Symbol
name = kwargs.get('name') or args[0]
assumptions, kwargs = cls._filter_assumptions(**kwargs)
# Note: use __xnew__ to bypass sympy caching
newobj = sympy.Symbol.__xnew__(cls, name, **assumptions)
# Initialization
newobj._dtype = cls.__dtype_setup__(**kwargs)
newobj.__init_finalize__(*args, **kwargs)
return newobj
__hash__ = Uncached.__hash__
class Scalar(Symbol, ArgProvider):
"""
Like a Symbol, but in addition it can pass runtime values to an Operator.
Parameters
----------
name : str
Name of the symbol.
dtype : data-type, optional
Any object that can be interpreted as a numpy data type. Defaults
to ``np.float32``.
is_const : bool, optional
True if the symbol value cannot be modified within an Operator,
False otherwise. Defaults to False.
**assumptions
Any SymPy assumptions, such as ``nonnegative=True``. Refer to the
SymPy documentation for more information.
"""
@classmethod
def __dtype_setup__(cls, **kwargs):
return kwargs.get('dtype', np.float32)
@property
def default_value(self):
return None
@property
def _arg_names(self):
return (self.name,)
def _arg_defaults(self, **kwargs):
if self.default_value is None:
# It is possible that the Scalar value is provided indirectly
# through a wrapper object (e.g., a Dimension spacing `h_x` gets its
# value via a Grid object)
return {}
else:
return {self.name: self.default_value}
def _arg_values(self, **kwargs):
if self.name in kwargs:
return {self.name: kwargs.pop(self.name)}
else:
return self._arg_defaults()
class AbstractTensor(sympy.ImmutableDenseMatrix, Basic, Pickable, Evaluable):
"""
Base class for vector and tensor valued functions. It inherits from and
mimicks the behavior of a sympy.ImmutableDenseMatrix.
The sub-hierachy is as follows
AbstractTensor
|
TensorFunction
|
---------------------------------
| |
VectorFunction TensorTimeFunction
\\-------\\ |
\\------- VectorTimeFunction
There are four relevant AbstractTensor sub-types: ::
* TensorFunction: A space-varying tensor valued function.
* VectorFunction: A space-varying vector valued function.
* TensorTimeFunction: A time-space-varying tensor valued function.
* VectorTimeFunction: A time-space-varying vector valued function.
"""
# SymPy attributes
is_MatrixLike = True
is_Matrix = True
# Devito attributes
is_AbstractTensor = True
is_TensorValued = True
is_VectorValued = False
@classmethod
def _new(cls, *args, **kwargs):
if args:
try:
# Constructor if input is (rows, cols, lambda)
newobj = super()._new(*args)
except ValueError:
# Constructor if input is list of list as (row, cols, list_of_list)
# doesn't work as it expects a flattened.
newobj = super()._new(args[2])
# Filter grid and dimensions
grid, dimensions = newobj._infer_dims()
if grid is None and dimensions is None:
return sympy.ImmutableDenseMatrix(*args)
# Initialized with constructed object
newobj.__init_finalize__(newobj.rows, newobj.cols, newobj.flat(),
grid=grid, dimensions=dimensions)
else:
# Initialize components and create new Matrix from standard
# Devito inputs
comps = cls.__subfunc_setup__(*args, **kwargs)
newobj = super()._new(comps)
newobj.__init_finalize__(*args, **kwargs)
return newobj
@classmethod
def _fromrep(cls, rep):
"""
This the new constructor mechanism for matrices in sympy 1.9.
Standard new object go through `_new` but arithmetic operations directly use
the representation based one.
This class method is only accessible from an existing AbstractTensor
that contains a grid or dimensions.
"""
newobj = super()._fromrep(rep)
grid, dimensions = newobj._infer_dims()
try:
# This is needed when `_fromrep` is called directly in 1.9
# for example with mul.
newobj.__init_finalize__(newobj.rows, newobj.cols, newobj.flat(),
grid=grid, dimensions=dimensions)
except TypeError:
# We can end up here when `_fromrep` is called through the default _new
# when input `comps` don't have grid or dimensions. For example
# `test_non_devito_tens` in `test_tensor.py`.
pass
return newobj
@classmethod
def __subfunc_setup__(cls, *args, **kwargs):
"""Setup each component of the tensor as a Devito type."""
return []
@property
def grid(self):
"""
A Tensor is expected to have all its components defined over the same grid
"""
grids = {getattr(c, 'grid', None) for c in self.flat()} - {None}
if len(grids) == 0:
return None
assert len(grids) == 1
return grids.pop()
def _infer_dims(self):
grids = {getattr(c, 'grid', None) for c in self.flat()} - {None}
dimensions = {d for c in self.flat()
for d in getattr(c, 'dimensions', ())} - {None}
# If none of the components are devito objects, returns a sympy Matrix
if len(grids) == 0 and len(dimensions) == 0:
return None, None
elif len(grids) > 0:
dimensions = None
assert len(grids) == 1
grid = grids.pop()
else:
grid = None
dimensions = tuple(dimensions)
return grid, dimensions
def flat(self):
try:
return super().flat()
except AttributeError:
return self._mat
def __init_finalize__(self, *args, **kwargs):
pass
__hash__ = sympy.ImmutableDenseMatrix.__hash__
def doit(self, **hint):
return self
def transpose(self, inner=True):
new = super().transpose()
if inner:
return new.applyfunc(lambda x: getattr(x, 'T', x))
return new
def adjoint(self, inner=True):
# Real valued adjoint is transpose
return self.transpose(inner=inner)
@call_highest_priority('__radd__')
def __add__(self, other):
try:
# Most case support sympy add
return super().__add__(other)
except TypeError:
# Sympy doesn't support add with scalars
return self.applyfunc(lambda x: x + other)
def _eval_matrix_mul(self, other):
"""
Copy paste from sympy to avoid explicit call to sympy.Add
TODO: fix inside sympy
"""
other_len = other.rows*other.cols
new_len = self.rows*other.cols
new_mat = [self.zero]*new_len
# If we multiply an n x 0 with a 0 x m, the
# expected behavior is to produce an n x m matrix of zeros
if self.cols != 0 and other.rows != 0:
self_cols = self.cols
mat = self.flat()
try:
other_mat = other.flat()
except AttributeError:
other_mat = other._mat
for i in range(new_len):
row, col = i // other.cols, i % other.cols
row_indices = range(self_cols*row, self_cols*(row+1))
col_indices = range(col, other_len, other.cols)
vec = [mat[a]*other_mat[b] for a, b in zip(row_indices, col_indices)]
new_mat[i] = sum(vec)
# Get new class and return product
newcls = self.classof_prod(other, new_mat)
return newcls._new(self.rows, other.cols, new_mat, copy=False)
class AbstractFunction(sympy.Function, Basic, Pickable, Evaluable):
"""
Base class for tensor symbols, cached by both SymPy and Devito. It inherits
from and mimicks the behaviour of a sympy.Function.
The hierarchy is structured as follows
AbstractFunction
|
---------------------------------
| |
DiscreteFunction Array
|
----------------------------------------
| |
| AbstractSparseFunction
| |
| -----------------------------------------------------
| | | |
Function SparseFunction AbstractSparseTimeFunction PrecomputedSparseFunction
| | | |
| | ------------------------------------ --------
| | | | |
TimeFunction SparseTimeFunction PrecomputedSparseTimeFunction
There are five relevant AbstractFunction sub-types: ::
* Array: A function that does not carry data.
* Function: A space-varying discrete function, which carries user data.
* TimeFunction: A time- and space-varying discrete function, which carries
user data.
* SparseFunction: A space-varying discrete function representing "sparse"
points, i.e. points that are not aligned with the
computational grid.
* SparseTimeFunction: A time- and space-varying function representing "sparse"
points, i.e. points that are not aligned with the
computational grid.
* PrecomputedSparseFunction: A SparseFunction that uses a custom interpolation
scheme, instead of linear interpolators.
* PrecomputedSparseTimeFunction: A SparseTimeFunction that uses a custom
interpolation scheme, instead of linear
interpolators.
"""
# SymPy attributes, explicitly say these are not Matrices
is_MatrixLike = False
is_Matrix = False
is_AbstractFunction = True
# SymPy default assumptions
is_real = True
is_imaginary = False
is_commutative = True
# Devito default assumptions
is_regular = True
"""
True if data and iteration points are aligned. Cases where they won't be
aligned (currently unsupported): Functions defined on SubDomains; compressed
Functions; etc.
"""
is_autopaddable = False
"""
True if the Function can be padded automatically by the Devito runtime,
thus increasing its size, False otherwise. Note that this property has no
effect if autopadding is disabled, which is the default behavior.
"""
__rkwargs__ = ('name', 'dtype', 'grid', 'halo', 'padding', 'ghost',
'alias', 'space', 'function')
def __new__(cls, *args, **kwargs):
# Preprocess arguments
args, kwargs = cls.__args_setup__(*args, **kwargs)
# Extract the `indices`, as perhaps they're explicitly provided
dimensions, indices = cls.__indices_setup__(*args, **kwargs)
# If it's an alias or simply has a different name, ignore `function`.
# These cases imply the construction of a new AbstractFunction off
# an existing one! This relieves the pressure on the caller by not
# requiring `function=None` explicitly at rebuild
name = kwargs.get('name')
alias = kwargs.get('alias')
function = kwargs.get('function')
if alias or (function and function.name != name):
function = kwargs['function'] = None
# If same name/indices and `function` isn't None, then it's
# definitely a reconstruction
if function is not None and \
function.name == name and \
function.indices == indices:
# Special case: a syntactically identical alias of `function`, so
# let's just return `function` itself
return function
with sympy_mutex:
# Go straight through Basic, thus bypassing caching and machinery
# in sympy.Application/Function that isn't really necessary
# AbstractFunctions are unique by construction!
newobj = sympy.Basic.__new__(cls, *sympy.sympify(indices))
# Initialization. The following attributes must be available
# when executing __init_finalize__
newobj._name = name
newobj._dimensions = dimensions
newobj._shape = cls.__shape_setup__(**kwargs)
newobj._dtype = cls.__dtype_setup__(**kwargs)
# All objects created off an existing AbstractFunction `f` (e.g.,
# via .func, or .subs, such as `f(x + 1)`) keep a reference to `f`
# through the `function` field
newobj.function = function or newobj
newobj.__init_finalize__(*args, **kwargs)
return newobj
def __init__(self, *args, **kwargs):
# no-op, the true init is performed by __init_finalize__
pass
def __str__(self):
return "%s(%s)" % (self.name, ', '.join(str(i) for i in self.indices))
__repr__ = __str__
def _sympystr(self, printer, **kwargs):
return str(self)
_latex = _sympystr
def _pretty(self, printer, **kwargs):
return printer._print_Function(self, func_name=self.name)
def __eq__(self, other):
try:
return (self.function is other.function and
self.indices == other.indices)
except AttributeError:
# `other` not even an AbstractFunction
return False
__hash__ = sympy.Function.__hash__
def _hashable_content(self):
return super()._hashable_content() + (id(self.function), self.indices)
@sympy.cacheit
def sort_key(self, order=None):
# Ensure that `f(x)` appears before `g(x)`
# With the legacy caching framework this wasn't necessary because
# the function name was already encoded in the class_key
class_key, args, exp, coeff = super().sort_key(order=order)
args = (len(args[1]) + 1, (self.name,) + args[1])
return class_key, args, exp, coeff
def __init_finalize__(self, *args, **kwargs):
# Setup halo, padding, and ghost regions
self._is_halo_dirty = False
self._halo = self.__halo_setup__(**kwargs)
self._padding = self.__padding_setup__(**kwargs)
self._ghost = self.__ghost_setup__(**kwargs)
# There may or may not be a `Grid`
self._grid = kwargs.get('grid')
# A `Distributor` to handle domain decomposition
self._distributor = self.__distributor_setup__(**kwargs)
# Symbol properties
# "Aliasing" another AbstractFunction means that `self` logically
# represents another object. For example, `self` might be used as the
# formal parameter of a routine generated by the compiler, where the
# routines is applied to several actual DiscreteFunctions
self._alias = kwargs.get('alias', False)
# The memory space of the AbstractFunction
# See `_mem_{local,mapped,host}.__doc__` for more info
self._space = kwargs.get('space', 'mapped')
assert self._space in ['local', 'mapped', 'host']
@classmethod
def __args_setup__(cls, *args, **kwargs):
"""
Preprocess *args and **kwargs before object initialization.
Notes
-----
This stub is invoked only if a look up in the cache fails.
"""
return args, kwargs
@classmethod
def __indices_setup__(cls, *args, **kwargs):
"""Extract the object indices from ``kwargs``."""
return (), ()
@classmethod
def __shape_setup__(cls, **kwargs):
"""Extract the object shape from ``kwargs``."""
return ()
@classmethod
def __dtype_setup__(cls, **kwargs):
"""Extract the object data type from ``kwargs``."""
return None
def __halo_setup__(self, **kwargs):
halo = tuple(kwargs.get('halo', ((0, 0),)*self.ndim))
return DimensionTuple(*halo, getters=self.dimensions)
def __padding_setup__(self, **kwargs):
padding = tuple(kwargs.get('padding', ((0, 0),)*self.ndim))
return DimensionTuple(*padding, getters=self.dimensions)
def __padding_setup_smart__(self, **kwargs):
nopadding = ((0, 0),)*self.ndim
if kwargs.get('autopadding', configuration['autopadding']):
# The padded Dimension
candidates = self.space_dimensions