-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathdimension.py
More file actions
1869 lines (1476 loc) · 56.1 KB
/
dimension.py
File metadata and controls
1869 lines (1476 loc) · 56.1 KB
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 math
from collections import namedtuple
from contextlib import suppress
from functools import cached_property
import numpy as np
import sympy
from sympy.core.decorators import call_highest_priority
from devito.data import LEFT, RIGHT
from devito.deprecations import deprecations
from devito.exceptions import InvalidArgument
from devito.logger import debug
from devito.tools import Pickable, is_integer, is_number, memoized_meth
from devito.types.args import ArgProvider
from devito.types.basic import DataSymbol, Scalar, Symbol
from devito.types.constant import Constant
from devito.types.relational import relational_max, relational_min
__all__ = [
'BlockDimension',
'ConditionalDimension',
'CustomDimension',
'DefaultDimension',
'Dimension',
'IncrDimension',
'ModuloDimension',
'MultiSubDimension',
'SpaceDimension',
'Spacing',
'StencilDimension',
'SteppingDimension',
'SubDimension',
'TimeDimension',
'VirtualDimension',
'dimensions',
]
SubDimensionThickness = namedtuple('SubDimensionThickness', 'left right')
class Dimension(ArgProvider):
"""
Symbol defining an iteration space.
A Dimension represents a problem dimension. It is typically used to index
into Functions, but it can also appear in the middle of a symbolic expression
just like any other symbol.
Dimension is the root of a hierarchy of classes, which looks as follows (only
the classes exposed to the level of the user API are shown)::
Dimension
|
---------------------------
| |
DerivedDimension DefaultDimension
|
---------------------
| |
SubDimension ConditionalDimension
Parameters
----------
name : str
Name of the dimension.
spacing : symbol, optional, default=h_name
A symbol to represent the physical spacing along this Dimension.
Examples
--------
Dimensions are automatically created when a Grid is instantiated.
>>> from devito import Grid
>>> grid = Grid(shape=(4, 4))
>>> x, y = grid.dimensions
>>> type(x)
<class 'devito.types.dimension.SpaceDimension'>
>>> time = grid.time_dim
>>> type(time)
<class 'devito.types.dimension.TimeDimension'>
>>> t = grid.stepping_dim
>>> type(t)
<class 'devito.types.dimension.SteppingDimension'>
Alternatively, one can create Dimensions explicitly
>>> from devito import Dimension
>>> i = Dimension(name='i')
Or, when many "free" Dimensions are needed, with the shortcut
>>> from devito import dimensions
>>> i, j, k = dimensions('i j k')
A Dimension can be used to build a Function as well as within symbolic
expressions, as both array index ("indexed notation") and free symbol.
>>> from devito import Function
>>> f = Function(name='f', shape=(4, 4), dimensions=(i, j))
>>> f + f
2*f(i, j)
>>> f[i + 1, j] + f[i, j + 1]
f[i, j + 1] + f[i + 1, j]
>>> f*i
i*f(i, j)
"""
is_Dimension = True
is_Space = False
is_Time = False
is_Default = False
is_Custom = False
is_Derived = False
is_NonlinearDerived = False
is_AbstractSub = False
is_Sub = False
is_MultiSub = False
is_Conditional = False
is_Stepping = False
is_Stencil = False
is_SubIterator = False
is_Modulo = False
is_Incr = False
is_Block = False
is_Virtual = False
# Prioritize self's __add__ and __sub__ to construct AffineIndexAccessFunction
_op_priority = sympy.Expr._op_priority + 1.
__rargs__ = ('name',)
__rkwargs__ = ('spacing',)
def __new__(cls, *args, **kwargs):
"""
Equivalent to ``BasicDimension(*args, **kwargs)``.
Notes
-----
This is only necessary for backwards compatibility, as originally
there was no BasicDimension (i.e., Dimension was just the top class).
"""
if cls is Dimension:
return BasicDimension(*args, **kwargs)
else:
return BasicDimension.__new__(cls, *args, **kwargs)
@classmethod
def class_key(cls):
"""
Overrides sympy.Symbol.class_key such that Dimensions always
precede other symbols when printed (e.g. x + h_x, not h_x + x).
"""
a, b, c = super().class_key()
return a, b - 1, c
@classmethod
def __dtype_setup__(cls, **kwargs):
# Unlike other Symbols, Dimensions can only be integers
return np.int32
def __str__(self):
return self.name
def _hashable_content(self):
return tuple(getattr(self, i) for i in self.__rargs__ + self.__rkwargs__)
@property
def spacing(self):
"""Symbol representing the physical spacing along the Dimension."""
return self._spacing
@cached_property
def symbolic_size(self):
"""Symbolic size of the Dimension."""
return Scalar(name=self.size_name, dtype=np.int32, is_const=True)
@cached_property
def symbolic_min(self):
"""Symbol defining the minimum point of the Dimension."""
return Scalar(name=self.min_name, dtype=np.int32, is_const=True)
@cached_property
def symbolic_max(self):
"""Symbol defining the maximum point of the Dimension."""
return Scalar(name=self.max_name, dtype=np.int32, is_const=True)
@property
def symbolic_incr(self):
"""The increment value while iterating over the Dimension."""
return sympy.S.One
@cached_property
def size_name(self):
return f"{self.name}_size"
@cached_property
def min_name(self):
return f"{self.name}_m"
@cached_property
def max_name(self):
return f"{self.name}_M"
@property
def indirect(self):
return False
@property
def index(self):
return self
@property
def is_const(self):
return False
@property
def root(self):
return self
@cached_property
def bound_symbols(self):
candidates = [self.symbolic_min, self.symbolic_max, self.symbolic_size,
self.symbolic_incr]
return frozenset(i for i in candidates if not i.is_Number)
@property
def _maybe_distributed(self):
"""Could it be a distributed Dimension?"""
return True
@cached_property
def _defines(self):
return frozenset({self})
@call_highest_priority('__radd__')
def __add__(self, other):
return AffineIndexAccessFunction(self, other)
@call_highest_priority('__add__')
def __radd__(self, other):
return AffineIndexAccessFunction(self, other)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return AffineIndexAccessFunction(self, -other)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return AffineIndexAccessFunction(other, -self)
@property
def _arg_names(self):
"""Tuple of argument names introduced by the Dimension."""
return (self.name, self.size_name, self.max_name, self.min_name)
def _arg_defaults(self, _min=None, size=None, alias=None):
"""
A map of default argument values defined by the Dimension.
Parameters
----------
_min : int, optional
Minimum point as provided by data-carrying objects.
size : int, optional
Size as provided by data-carrying symbols.
alias : Dimension, optional
To get the min/max/size names under which to store values. Use
self's if None.
"""
dim = alias or self
return {dim.min_name: _min or 0,
dim.size_name: size,
dim.max_name: size if size is None else size-1}
def _arg_values(self, interval, grid=None, args=None, **kwargs):
"""
Produce a map of argument values after evaluating user input. If no user
input is provided, get a known value in ``args`` and adjust it so that no
out-of-bounds memory accesses will be performeed. The adjustment exploits
the information in ``interval``, an Interval describing the Dimension data
space. If no value is available in ``args``, use a default value.
Parameters
----------
interval : Interval
Description of the Dimension data space.
grid : Grid, optional
Used for spacing overriding and MPI execution; if ``self`` is a distributed
Dimension, then ``grid`` is used to translate user input into rank-local
indices.
**kwargs
Dictionary of user-provided argument overrides.
"""
# Fetch user input and convert into rank-local values
glb_minv = kwargs.pop(self.min_name, None)
glb_maxv = kwargs.pop(self.max_name, kwargs.pop(self.name, None))
if grid is not None and grid.is_distributed(self):
loc_minv, loc_maxv = grid.distributor.glb_to_loc(self, (glb_minv, glb_maxv))
else:
loc_minv, loc_maxv = glb_minv, glb_maxv
# If no user-override provided, use a suitable default value
defaults = self._arg_defaults()
if glb_minv is None:
loc_minv = args.get(self.min_name, defaults[self.min_name])
with suppress(AttributeError, TypeError):
loc_minv -= min(interval.lower, 0)
if glb_maxv is None:
loc_maxv = args.get(self.max_name, defaults[self.max_name])
with suppress(AttributeError, TypeError):
loc_maxv -= max(interval.upper, 0)
# Some `args` may still be DerivedDimensions' defaults. These, in turn,
# may represent sets of legal values. If that's the case, here we just
# pick one. Note that we sort for determinism
try:
loc_minv = loc_minv.stop
except AttributeError:
with suppress(TypeError):
loc_minv = sorted(loc_minv).pop(0)
try:
loc_maxv = loc_maxv.stop
except AttributeError:
with suppress(TypeError):
loc_maxv = sorted(loc_maxv).pop(0)
return {self.min_name: loc_minv, self.max_name: loc_maxv}
def _arg_check(self, args, size, interval):
"""
Raises
------
InvalidArgument
If any of the ``self``-related runtime arguments in ``args``
will cause an out-of-bounds access.
"""
if self.min_name not in args:
raise InvalidArgument(f"No runtime value for {self.min_name}")
if interval.is_Defined and args[self.min_name] + interval.lower < 0:
raise InvalidArgument(f"OOB detected due to "
f"{self.min_name}={args[self.min_name]}")
if self.max_name not in args:
raise InvalidArgument(f"No runtime value for {self.max_name}")
if interval.is_Defined:
if is_integer(interval.upper):
upper = interval.upper
else:
# Autopadding causes non-integer upper limit
from devito.symbolics import normalize_args
upper = interval.upper.subs(normalize_args(args))
if args[self.max_name] + upper >= size:
raise InvalidArgument(f"OOB detected due to "
f"{self.max_name}={args[self.max_name]}")
# Allow the specific case of max=min-1, which disables the loop
if args[self.max_name] < args[self.min_name]-1:
raise InvalidArgument(
f'Illegal {self.max_name}={args[self.max_name]} < '
f'{self.min_name}={args[self.min_name]}'
)
elif args[self.max_name] == args[self.min_name]-1:
debug("%s=%d and %s=%d might cause no iterations along Dimension %s",
self.min_name, args[self.min_name],
self.max_name, args[self.max_name], self.name)
# Pickling support
__reduce_ex__ = Pickable.__reduce_ex__
__getnewargs_ex__ = Pickable.__getnewargs_ex__
class Spacing(Scalar):
pass
class BasicDimension(Dimension, Symbol):
__doc__ = Dimension.__doc__
def __new__(cls, *args, **kwargs):
return Symbol.__new__(cls, *args, **kwargs)
def __init_finalize__(self, name, spacing=None, **kwargs):
self._spacing = spacing or Spacing(name=f'h_{name}', is_const=True)
def __eq__(self, other):
# Being of type Cached, Dimensions are by construction unique. But unlike
# Symbols, equality is much stricter -- we consider any two Dimensions
# equal iff they are the very same object. This has several advantages.
# First of all, it makes it much more difficult to trick the compiler
# to generate buggy code (e.g., using two different "x" Dimensions that
# actually represent the same iteration space). Secondly, comparison
# is much cheaper, since we avoid having to go through all of the
# __rargs__/__rkwargs__, and there can be quite a few depending on the
# specific Dimension type
return self is other
__hash__ = Symbol.__hash__
class DefaultDimension(Dimension, DataSymbol):
"""
Symbol defining an iteration space with statically-known size.
Parameters
----------
name : str
Name of the dimension.
spacing : Symbol, optional
A symbol to represent the physical spacing along this Dimension.
default_value : float, optional
Default value associated with the Dimension.
Notes
-----
A DefaultDimension carries a value, so it has a mutable state. Hence, it is
not cached.
"""
is_Default = True
def __new__(cls, *args, **kwargs):
return DataSymbol.__new__(cls, *args, **kwargs)
def __init_finalize__(self, name, spacing=None, default_value=None, **kwargs):
self._spacing = spacing or Spacing(name=f'h_{name}', is_const=True)
self._default_value = default_value or 0
@cached_property
def symbolic_size(self):
return sympy.Number(self._default_value)
def _arg_defaults(self, _min=None, size=None, alias=None):
dim = alias or self
size = size or dim._default_value
return {dim.min_name: _min or 0, dim.size_name: size,
dim.max_name: size if size is None else size-1}
class SpaceDimension(BasicDimension):
"""
Symbol defining an iteration space.
This symbol represents a space dimension that defines the extent of
a physical grid.
A SpaceDimension creates dedicated shortcut notations for spatial
derivatives on Functions.
Parameters
----------
name : str
Name of the dimension.
spacing : symbol, optional
A symbol to represent the physical spacing along this Dimension.
"""
is_Space = True
class TimeDimension(BasicDimension):
"""
Symbol defining an iteration space.
This symbol represents a time dimension that defines the extent of time.
A TimeDimension create dedicated shortcut notations for time derivatives
on Functions.
Parameters
----------
name : str
Name of the dimension.
spacing : symbol, optional
A symbol to represent the physical spacing along this Dimension.
"""
is_Time = True
class DerivedDimension(BasicDimension):
"""
Symbol defining an iteration space derived from a ``parent`` Dimension.
Parameters
----------
name : str
Name of the dimension.
parent : Dimension
The parent Dimension.
"""
is_Derived = True
__rargs__ = Dimension.__rargs__ + ('parent',)
__rkwargs__ = ()
def __init_finalize__(self, name, parent):
assert isinstance(parent, Dimension)
self._parent = parent
# Inherit time/space identifiers
self.is_Time = parent.is_Time
self.is_Space = parent.is_Space
@property
def parent(self):
return self._parent
@property
def index(self):
return self if self.indirect else self.parent
@property
def root(self):
return self._parent.root
@property
def spacing(self):
return self.parent.spacing
@cached_property
def _defines(self):
return frozenset({self}) | self.parent._defines
@property
def _arg_names(self):
return self.parent._arg_names
def _arg_check(self, *args, **kwargs):
"""A DerivedDimension performs no runtime checks."""
return
# ***
# The Dimensions below are exposed in the user API. They can only be created by
# the user
class Thickness(DataSymbol):
"""A DataSymbol to represent a thickness of a SubDimension"""
__rkwargs__ = DataSymbol.__rkwargs__ + ('root', 'side', 'local', 'value')
def __new__(cls, *args, root=None, side=None, local=False, **kwargs):
newobj = super().__new__(cls, *args, **kwargs)
newobj._root = root
newobj._side = side
newobj._local = local
return newobj
def __init_finalize__(self, *args, **kwargs):
self._value = kwargs.pop('value', None)
kwargs.setdefault('is_const', True)
super().__init_finalize__(*args, **kwargs)
@property
def root(self):
return self._root
@property
def side(self):
return self._side
@property
def local(self):
return self._local
@property
def value(self):
return self._value
def _arg_values(self, grid=None, **kwargs):
# Allow override of thickness values to disable BCs
# However, arguments from the user are considered global
# So overriding the thickness to a nonzero value should not cause
# boundaries to exist between ranks where they did not before
rtkn = kwargs.get(self.name, self.value)
if grid is not None and grid.is_distributed(self.root):
# Get local thickness
if self.local:
# Dimension is of type `left`/`right` - compute the offset
# and then add 1 to get the appropriate thickness
if self.value is not None:
tkn = grid.distributor.glb_to_loc(self.root, rtkn-1, self.side)
tkn = tkn+1 if tkn is not None else 0
else:
tkn = 0
else:
# Dimension is of type `middle`
tkn = grid.distributor.glb_to_loc(self.root, rtkn, self.side) or 0
else:
tkn = rtkn or 0
return {self.name: tkn}
class AbstractSubDimension(DerivedDimension):
"""
Symbol defining a convex iteration sub-space derived from a `parent`
Dimension.
Notes
-----
This is just the abstract base class for various types of SubDimensions.
"""
is_AbstractSub = True
__rargs__ = DerivedDimension.__rargs__ + ('thickness',)
__rkwargs__ = ()
_thickness_type = Thickness
def __init_finalize__(self, name, parent, thickness, **kwargs):
super().__init_finalize__(name, parent)
thickness = thickness or (None, None)
if any(isinstance(tkn, self._thickness_type) for tkn in thickness):
self._thickness = SubDimensionThickness(*thickness)
else:
self._thickness = self._symbolic_thickness(thickness=thickness)
@cached_property
def _interval(self):
left = self.parent.symbolic_min + self.ltkn
right = self.parent.symbolic_max - self.rtkn
return sympy.Interval(left, right)
@memoized_meth
def _symbolic_thickness(self, **kwargs):
kwargs = {'dtype': np.int32, 'is_const': True, 'nonnegative': True}
names = [f"{self.parent.name}_{s}tkn" for s in ('l', 'r')]
return SubDimensionThickness(*[Thickness(name=n, **kwargs) for n in names])
@cached_property
def symbolic_min(self):
return self._interval.left
@cached_property
def symbolic_max(self):
return self._interval.right
@cached_property
def symbolic_size(self):
# The size must be given as a function of the parent's symbols
return self.symbolic_max - self.symbolic_min + 1
@property
def thickness(self):
return self._thickness
tkns = thickness # Shortcut for thickness
@property
def ltkn(self):
# Shortcut for the left thickness symbol
return self.thickness.left
@property
def rtkn(self):
# Shortcut for the right thickness symbol
return self.thickness.right
def __hash__(self):
return id(self)
class SubDimension(AbstractSubDimension):
"""
Symbol defining a convex iteration sub-space derived from a ``parent``
Dimension.
Parameters
----------
name : str
Name of the dimension.
parent : Dimension
The parent Dimension.
left : expr-like
Symbolic expression providing the left (lower) bound of the
SubDimension.
right : expr-like
Symbolic expression providing the right (upper) bound of the
SubDimension.
thickness : 2-tuple of 2-tuples
The thickness of the left and right regions, respectively.
local : bool
True if, in case of domain decomposition, the SubDimension is
guaranteed not to span more than one domain, False otherwise.
Examples
--------
SubDimensions should *not* be created directly in user code; SubDomains
should be used instead. Exceptions are rare.
To create a SubDimension, one should use the shortcut methods ``left``,
``right``, ``middle``. For example, to create a SubDimension that spans
the entire space of the parent Dimension except for the two extremes:
>>> from devito import Dimension, SubDimension
>>> x = Dimension('x')
>>> xi = SubDimension.middle('xi', x, 1, 1)
For a SubDimension that only spans the three leftmost points of its
parent Dimension, instead:
>>> xl = SubDimension.left('xl', x, 3)
SubDimensions created via the ``left`` and ``right`` shortcuts are, by default,
local (i.e., non-distributed) Dimensions, as they are assumed to fit entirely
within a single domain. This is the most typical use case (e.g., to set up
boundary conditions). To drop this assumption, pass ``local=False``.
"""
is_Sub = True
__rargs__ = AbstractSubDimension.__rargs__ + ('local',)
_thickness_type = Thickness
def __init_finalize__(self, name, parent, thickness, local,
**kwargs):
self._local = local
super().__init_finalize__(name, parent, thickness)
@classmethod
def left(cls, name, parent, thickness, local=True):
return cls(name, parent, thickness=(thickness, None), local=local)
@classmethod
def right(cls, name, parent, thickness, local=True):
return cls(name, parent, thickness=(None, thickness), local=local)
@classmethod
def middle(cls, name, parent, thickness_left, thickness_right, local=False):
return cls(name, parent, thickness=(thickness_left, thickness_right), local=local)
@memoized_meth
def _symbolic_thickness(self, thickness=None):
kwargs = {'dtype': np.int32, 'is_const': True, 'nonnegative': True,
'root': self.root, 'local': self.local}
names = [f"{self.parent.name}_{s}tkn" for s in ('l', 'r')]
sides = [LEFT, RIGHT]
return SubDimensionThickness(*[
Thickness(name=n, side=s, value=t, **kwargs)
for n, s, t in zip(names, sides, thickness, strict=True)
])
@cached_property
def _interval(self):
if self.thickness.right.value is None: # Left SubDimension
left = self.parent.symbolic_min
right = self.parent.symbolic_min + self.ltkn - 1
elif self.thickness.left.value is None: # Right SubDimension
left = self.parent.symbolic_max - self.rtkn + 1
right = self.parent.symbolic_max
else: # Middle SubDimension
return super()._interval
return sympy.Interval(left, right)
@property
def local(self):
return self._local
@property
def is_left(self):
return self.thickness.right.value is None
@property
def is_right(self):
return self.thickness.left.value is None
@property
def is_middle(self):
return not self.is_left and not self.is_right
@cached_property
def bound_symbols(self):
# Add thickness symbols
return frozenset().union(*[i.free_symbols for i in super().bound_symbols])
@property
def _maybe_distributed(self):
return not self.local
@property
def _arg_names(self):
return tuple(k.name for k in self.thickness) + self.parent._arg_names
def _arg_defaults(self, grid=None, **kwargs):
return {}
def _arg_values(self, interval, grid=None, **kwargs):
# SubDimension thicknesses at runtime are calculated by the thicknesses
# themselves
return {}
class MultiSubDimension(AbstractSubDimension):
"""
A special Dimension to be used in MultiSubDomains.
"""
is_MultiSub = True
__rkwargs__ = ('functions', 'bounds_indices', 'implicit_dimension')
def __init_finalize__(self, name, parent, thickness, functions=None,
bounds_indices=None, implicit_dimension=None):
super().__init_finalize__(name, parent, thickness)
self.functions = functions
self.bounds_indices = bounds_indices
self.implicit_dimension = implicit_dimension
@cached_property
def bound_symbols(self):
return self.parent.bound_symbols
class SubsamplingFactor(Scalar):
pass
class ConditionalDimension(DerivedDimension):
"""
Symbol defining a non-convex iteration sub-space derived from a ``parent``
Dimension, implemented by the compiler generating conditional "if-then" code
within the parent Dimension's iteration space.
Parameters
----------
name : str
Name of the dimension.
parent : Dimension
The parent Dimension.
factor : int, optional, default=None
The number of iterations between two executions of the if-branch. If None
(default), ``condition`` must be provided.
condition : expr-like, optional, default=None
An arbitrary SymPy expression, typically involving the ``parent``
Dimension. When it evaluates to True, the if-branch is executed. If None
(default), ``factor`` must be provided.
indirect : bool, optional, default=False
If True, use `self`, rather than the parent Dimension, to
index into arrays. A typical use case is when arrays are accessed
indirectly via the ``condition`` expression.
relation: Or/And, default=And
How this ConditionalDimension will be combined with other ones during
lowering for example combining Function's ConditionalDimension with
an Equation's implicit_dim. All Dimensions within an equation
must have `Or` relation for the final combined condition to be Or.
Examples
--------
Among the other things, ConditionalDimensions are indicated to implement
Function subsampling. In the following example, an Operator evaluates the
Function ``g`` and saves its content into ``f`` every ``factor=4`` iterations.
>>> from devito import Dimension, ConditionalDimension, Function, Eq, Operator
>>> size, factor = 16, 4
>>> i = Dimension(name='i')
>>> ci = ConditionalDimension(name='ci', parent=i, factor=factor)
>>> g = Function(name='g', shape=(size,), dimensions=(i,))
>>> f = Function(name='f', shape=(int(size/factor),), dimensions=(ci,))
>>> op = Operator([Eq(g, 1), Eq(f, g)])
The Operator generates the following for-loop (pseudocode)
.. code-block:: C
for (int i = i_m; i <= i_M; i += 1) {
g[i] = 1;
if (i%4 == 0) {
f[i / 4] = g[i];
}
}
Another typical use case is when one needs to constrain the execution of
loop iterations so that certain conditions are honoured. The following
artificial example uses ConditionalDimension to guard against out-of-bounds
accesses in indirectly accessed arrays.
>>> from sympy import And
>>> ci = ConditionalDimension(name='ci', parent=i,
... condition=And(g[i] > 0, g[i] < 4, evaluate=False))
>>> f = Function(name='f', shape=(int(size/factor),), dimensions=(ci,))
>>> op = Operator(Eq(f[g[i]], f[g[i]] + 1))
The Operator generates the following for-loop (pseudocode)
.. code-block:: C
for (int i = i_m; i <= i_M; i += 1) {
if (g[i] > 0 && g[i] < 4) {
f[g[i]] = f[g[i]] + 1;
}
}
"""
is_NonlinearDerived = True
is_Conditional = True
__rkwargs__ = DerivedDimension.__rkwargs__ + \
('factor', 'condition', 'indirect', 'relation')
def __init_finalize__(self, name, parent=None, factor=None, condition=None,
indirect=False, relation=sympy.And, **kwargs):
# `parent=None` degenerates to a ConditionalDimension outside of
# any iteration space
if parent is None:
parent = BOTTOM
super().__init_finalize__(name, parent)
# Process subsampling factor
if factor is None:
self._factor = None
elif is_number(factor):
self._factor = int(factor)
elif factor.is_Constant:
_ = deprecations.constant_factor_warn
self._factor = factor
else:
raise ValueError("factor must be an integer")
self._condition = condition
self._indirect = indirect
self._relation = relation
@property
def uses_symbolic_factor(self):
return self._factor is not None
@property
def factor_data(self):
if isinstance(self.factor, Constant):
return self.factor.data
elif self.factor is not None:
return self.factor
else:
return 1
@property
def spacing(self):
return self.factor_data * self.parent.spacing
@property
def factor(self):
return self._factor
@cached_property
def symbolic_factor(self):
if not self.uses_symbolic_factor:
return None
elif isinstance(self.factor, Constant):
return self.factor
else:
return SubsamplingFactor(
name=f'{self.name}f', dtype=np.int32, is_const=True
)
@property
def condition(self):
return self._condition
@property
def indirect(self):
return self._indirect
@property
def relation(self):
return self._relation
@cached_property
def free_symbols(self):
retval = set(super().free_symbols)
if self.condition is not None:
retval |= self.condition.free_symbols
with suppress(AttributeError):
retval |= self.factor.free_symbols
return retval
def _arg_values(self, interval, grid=None, args=None, **kwargs):