File: ScriptElement.tmpl

package info (click to toggle)
xmds2 3.0.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 52,068 kB
  • sloc: python: 63,652; javascript: 9,230; cpp: 3,929; ansic: 1,463; makefile: 121; sh: 54
file content (627 lines) | stat: -rw-r--r-- 27,502 bytes parent folder | download
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
@shBang #!/usr/bin/env python3

@*
ScriptElement.tmpl

Created by Graham Dennis on 2007-08-23.

Copyright (c) 2007-2012, Graham Dennis

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

*@
@extends xpdeint._ScriptElement

@from xpdeint.CallOnceGuards import callOnceGuard

@*doc-class:
  This class provides all of the various loop constructs that are needed in the generated code.
  Currently, this class provides three different types of loop with differing levels of complexity:
  
  1.  `loopOverVectorsWithInnerContentTemplate`: This is the most basic form of a loop.
      This loop construct is for the occasions where you want to do the same operation to
      every component of a bunch of vectors. The perfect example of this case is in the 
      integrators where a derivative for each vector component has been calculated, and that
      needs to be added to the original vector in some way. Note that the operation performed
      by this loop must perform the same operation to the real and imaginary parts of a complex
      vector.
      
      This function generates one loop per vector, and the form of the loop generated for each vector is::
      
        for (long _i0 = 0; _i0 < _size_of_vector; _i0++) {
          // contents of loop
        }
      
      As the exact contents of the loops will be different for each vector as each vector has a
      different array name, and a different size, instead of providing the exact contents of the loop,
      you provide a Cheetah template string for the loop contents describing the loop contents.
      
      Due to the very simple nature of this loop, it can be threaded quite easily using the OpenMP
      feature (if it is turned on), or the code modified to make most compilers' auto-vectorisation
      features vectorise the code (if the auto-vectorisation feature is turned on).
      
  2.  `loopOverVectorsInSpaceWithInnerContent`: This one is slightly more complex than the previous type,
      and so has slightly different restrictions. This loop construct is for the occasions where you want
      to do the same operation at each point, but possibly different operations to different components.
      An additional restriction for this loop construct is that all of the vectors must be in the same
      field. This is because unlike the previous loop construct, only one loop is created, and all of
      the vectors are made available in that loop. This loop construct also creates ``#define``s for
      components of vectors, but only the ``phi`` form, not the integer-valued ``phi[i, j]`` form as
      well.
      
      The form of the loop generated by this function is::
      
        // #define's and creation of index pointers for each vector
        for (long _i0 = 0; _i0 < _size_of_field_all_vectors_are_in; _i0++) {
          // contents of loop
          
          // increment each vector's index pointer by the number of components in the vector.
        }
      
      For this loop construct, the contents of the loop are simply transplanted inside the loop, i.e.
      it isn't interpreted as a Cheetah template string.
      
      As this loop can contain arbitrary operations on complex vectors, this loop cannot be auto-vectorised.
      However, it can still be threaded with the OpenMP feature.
     
  3. `loopOverFieldInBasisWithVectorsAndInnerContent`: By far the most powerful loop construct available.
     This is the loop construct you want with user-provided code. It allows you to loop over all of the 
     dimensions of a given field in a given space (arbitrary combination of fourier and non-fourier space),
     making various vectors available which may or may not come from the same field as the looping field.
     This loop construct can be used for integrating over dimensions for moments, sub-sampling, etc.
     
     This function supports a number of optional arguments to enable customisation of the generated loops.
     As this loop could contain arbitrary code, it can neither be vectorised nor threaded using OpenMP.
     
     See the documentation of the function for more details.
     
  
  
  Although this class might look a bit like black magic, I promise that it is not self-aware, and
  probably won't take over the universe. However, should it attempt to do so, I'll provide a copy of the 3
  laws for its own reference:
  
  1.  xpdeint may not injure a user or, through inaction, allow a user to come to harm.
  
  2.  xpdeint must obey orders given to it by the user, except where such orders would conflict with the First Law.
  
  3.  xpdeint must protect its own existence as long as such protection does not conflict with the First or Second Law.
*@


@def loopOverVectorsWithInnerContentTemplate($vectors, $templateString, $basis = None)
@*doc:
Insert code to loop over a vector.

The contents of the loop are specified by a Cheetah template string,
which has the following variables available:

  - ``$vector``:   The current vector
  - ``$index``:   The index variable name

A simple example for the contents of this loop would be (passed as a `templateString`)::

  _active_${vector.id}[${index}] $operation;

Where ``$operation`` is some operation. If the `templateString` does not end with a new line,
then one is added automatically.

The intention is that this function is to be used when you have a very simple operation
to be performed in the same way on a range of vectors in possibly different fields.
*@
  @assert len($templateString) > 0
  @#
  @set $templateFeatureOrdering = ['AutoVectorise']
  @set $dict = {'templateString': $templateString,
                'originalTemplateString': $templateString,
                'loopCountPrefixFunction': None,
                'templateFunctions': []}
  @silent $insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateModifyTemplate',
                                 $templateFeatureOrdering,
                                 $dict)
  @set $templateString = dict['templateString']
  @# If the loopCountPrefixFunction is None, then provide an empty default
  @set $loopCountPrefixFunction = dict['loopCountPrefixFunction'] or (lambda v: '')
  @#
  @# The template string should end with a new line, if it doesn't we'll add it
  @if $templateString[-1] != '\n'
    @set $templateString = $templateString + '\n'
  @end if
  @#
  @set $templateString += '\n'.join(dict['templateFunctions'])
  @#
  @set $templateVariables = {'index': '_i0'}
  @set $innerLoopTemplate = $templateObjectFromStringWithTemplateVariables($templateString, $templateVariables)
  @#
  @set $loopFeatureOrdering = ['AutoVectorise', 'OpenMP']
  @silent $dict['extraIndent'] = 0
  @silent $dict['template'] = $innerLoopTemplate
  @for $vector in $vectors
    @#
    @# Get the loopCountPrefix from the loopCountPrefixFunction
    @set $loopCountPrefix = $loopCountPrefixFunction($vector)
    @#
    @# Set the template's current vector
    @silent $templateVariables['vector'] = $vector
${insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateBegin', $loopFeatureOrdering, $dict)}@slurp
    @capture loopString
      @if basis is None
        @set $vectorSize = vector.allocSize
      @else
        @set $vectorSize = vector.sizeInBasis(basis)
      @end if
for (long _i0 = 0; _i0 < ${loopCountPrefix}${vectorSize}; _i0++) {
  ${innerLoopTemplate, autoIndent=True}@slurp
}
    @end capture
${loopString, extraIndent=dict['extraIndent']}
${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentTemplateEnd', $loopFeatureOrdering, $dict)}@slurp
  @end for
@end def

@def loopOverVectorsInBasisWithInnerContent($vectors, $basis, $innerContent)
@*doc:
Insert code to loop over vectors in a single field.
Unlike the previous function, this function loops over a single field
and only provides access to vectors in that field.

The intention is that this function is used where a specific operation
needs to be performed that does not require loops over individual dimensions,
and so the resulting code can be simplified, and possibly made easier to
optimise in the future with vectorisation and OpenMP.
*@
  @# All of the vectors must be in the same field
  @set $fields = set([v.field for v in $vectors])
  @#
  @assert len($fields) == 1
  @set $field = $anyObject($fields)
  @#
  @set $featureOrdering = ['OpenMP']
  @#
  @set $blankLineSeparator = ''
  @#
  @# Initialise index pointers
  @for $vector in $vectors
    @# Don't output a blank line for the first vector
${blankLineSeparator}@slurp
    @set $blankLineSeparator = '\n'
    @#
long _${vector.id}_index_pointer = 0;
    @#
    @for $componentNumber, $componentName in enumerate($vector.components)
#define $componentName _active_${vector.id}[_${vector.id}_index_pointer + $componentNumber]
    @end for
  @end for
  @set $dict = {'vectors': $vectors, 'loopCode': innerContent}
${insertCodeForFeatures('loopOverVectorsWithInnerContentBegin', $featureOrdering, $dict)}@slurp
for (long _i0 = 0; _i0 < ${field.sizeInBasis(basis)}; _i0++) {
  ${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentEnd', $featureOrdering, $dict), autoIndent=True}@slurp
  @#
  ${innerContent, autoIndent=True}@slurp

  @for $vector in $vectors
  _${vector.id}_index_pointer += _${vector.id}_ncomponents;
  @end for
}
  @for $vector in $vectors
    @for $componentName in $vector.components
#undef $componentName
    @end for
  @end for
  @#
@end def

@def loopOverFieldInBasisWithVectorsAndInnerContent($field, $basis, $vectors, $innerLoopCode, $indexOverrides = None, $vectorOverrides = None, $loopingOrder = _ScriptElement.LoopingOrder.MemoryOrder, $preDimensionLoopOpeningCode = None, $postDimensionLoopClosingCode = None, vectorsNotNeedingDefines = None)
@*doc:
Insert code to loop over a fields points making available the given vectors
Note that this code asserts that the field that will be iterated over is at
most as fine as the fields underlying the vectors in each dimension that has
more than one point.

Note that the vectors CAN be from fields other than ``$field``, this makes it easy
to use this code for moment groups. The only restriction is that the fields
for the vectors cannot be coarser than ``$field`` (in dimensions that have more
than one point). Though this could be changed if a use-case for this can be
found such that the meaning of this would be well-defined.

Optional arguments:

  - `indexOverrides`: instead of looping over a dimension, use a specific value for its index.
    This should be a dictionary mapping dimension names to a dictionary of field -> override
    string pairs.
    
    For example, if you want to override the propagation dimension (``t``)::
    
      { 't': {some_field: 'some_t_index_for_field', some_other_field: 'etc'}}
    
  - `vectorOverrides`: instead of causing the component names to be directly mapped to the arrays
    create variables for each component.
  
  - `loopingOrder`: One of the values of the `LoopingOrder` class. i.e. MemoryOrder, StrictlyAscendingOrder
    or StrictlyDescendingOrder. For example, StrictlyAscendingOrder causes the loops over kspace dimensions
    to be performed in strictly ascending order instead of starting at 0, working up to the maximum value,
    and then doing the negative values in increasing order.
  
  - `preDimensionLoopOpeningCode`: a dictionary containing code to be put in the loop structure before
    the loop for a given dimension has been opened. For example, if you want to insert code before the
    ``x`` dimension, you would pass the following for `postDimensionLoopOpeningCode`::
    
      { 'x': lotsAndLotsOfPreLoopCode }
    
    Note that ``x`` must be the name of the dimension representation, not the dimension itself. i.e. ``kx`` instead
    of ``x`` if the dimension is in Fourier space. This note applies to `postDimensionLoopClosingCode` as well.
  
  - `postDimensionLoopClosingCode`: a dictionary containing code to be put in the loop structure after
    the loop for a given dimension has been closed. For example, if you want to insert code after the
    ``x`` dimension, you would pass the following for `postDimensionLoopClosingCode`::
    
      { 'x': lotsAndLotsOfPostLoopCode }
    
  - `vectorsNotNeedingDefines`: a set of vectors for which C ``#define`` statements for vector components are
    not wanted.

*@
  @#
  @# Defaults
  @#
  @set indexOverrides = indexOverrides or {}
  @set vectorOverrides = vectorOverrides or []
  @set preDimensionLoopOpeningCode = preDimensionLoopOpeningCode or {}
  @set postDimensionLoopClosingCode = postDimensionLoopClosingCode or {}
  @set vectorsNotNeedingDefines = vectorsNotNeedingDefines or set()
  @#
  @set $featureOrdering = ['Driver']
  @set $featuresDict = { 'field': field,
                         'basis': basis,
                         'vectors': vectors,
                         'indexOverrides': indexOverrides,
                         'vectorOverrides': vectorOverrides,
                         'preDimensionLoopOpeningCode': preDimensionLoopOpeningCode,
                         'postDimensionLoopClosingCode': postDimensionLoopClosingCode,
                       }
${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict)}@slurp
  @#
  @# Some vectors will need to have their index pointers set explicitly.
  @# These will be those which belong to fields with different dimensions.
  @set $vectorsRequiringExplictIndexPointers = set([v for v in vectors if v.field.dimensions != field.dimensions])
  @# 
  @# If we have a loopingOrder other than MemoryOrder, then the vectors in
  @# field $field will also need their index pointers set explicitly
  @if $loopingOrder != $LoopingOrder.MemoryOrder
    @silent vectorsRequiringExplictIndexPointers.update($vectors)
  @end if
  @#
  @# Now determine the vectors not requiring explicit index pointers
  @set $vectorsNotRequiringExplicitIndexPointers = set(vectors).difference(vectorsRequiringExplictIndexPointers)
  @#
  @set $indentLevel = 0
  @#
  @# Initialise index pointers
  @for $vector in $vectors
    @#
long _${vector.id}_index_pointer = 0;
    @if vector in vectorsNotNeedingDefines
      @pass
    @elif vector in vectorOverrides
      @# This vector is in vectorOverrides, so instead of #defining, we want to create variables
      @for componentName in vector.components
$vector.type $componentName;
      @end for
    @else
      @# If vector isn't in vectorOverrides or vectorsNotNeedingDefines, then we want to #define the vector's components
      @for $componentNumber, $componentName in enumerate($vector.components)
#define $componentName _active_${vector.id}[_${vector.id}_index_pointer + $componentNumber]
      @end for
    @end if
  @end for
  @# loop over geometry dimensions creating dimension variable names for those that
  @# aren't in this field, but are in any of the $vectors fields, unless we have an index override for it.
  @for $dimension in $geometry.dimensions
    @if $field.hasDimension($dimension)
      @continue
    @end if
    @#
    @if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0
      @continue
    @end if
    @#
    @set $dimRep = dimension.inBasis(basis)
    @if dimRep.name in indexOverrides
      @continue
    @end if

${dimRep.createCoordinateVariableForSinglePointSample}@slurp

  @end for
  @#
  @# loop over the dimensions opening the loops
  @set $lastLoopDimRep = None
  @for dimRep in field.inBasis(basis)
    @#
    @if dimRep.name in preDimensionLoopOpeningCode
${preDimensionLoopOpeningCode[$dimRep.name], extraIndent=$indentLevel}@slurp
    @end if
    @if not dimRep.name in indexOverrides
      @# If there isn't an indexOverride for this dimension, then open a loop
      @set $lastLoopDimRep = dimRep
      @#
      @set $loopOpeningFeatureOrdering = ['OpenMP']
      @silent featuresDict.update({
        'vectorsNotRequiringExplicitIndexPointers': vectorsNotRequiringExplicitIndexPointers,
        'dimRep': dimRep,
        'loopCode': innerLoopCode
      })
${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}@slurp
      @#
${dimRep.openLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}@slurp
      @set $indentLevel = $indentLevel + 2
${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}@slurp
    @else
      @# We have an indexOverride for this dimension. 
${prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides), extraIndent=$indentLevel}@slurp
    @end if
    @#
  @end for
  @#
  @set $result = $setExplicitIndexPointersForVectorsWithFieldAndBasis(vectorsRequiringExplictIndexPointers, field, basis, indexOverrides)
  @if result
${result, extraIndent=indentLevel}@slurp
  @end if
  @#
${innerLoopCode, extraIndent=$indentLevel}@slurp
${epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(vectorOverrides, field, basis), extraIndent=indentLevel}@slurp
  @#
  @if lastLoopDimRep
    @# Increment the index pointers. This needs to be in a function in order to be able
    @# to use the variable indentation required
${incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep), extraIndent=indentLevel}@slurp
  @end if
  @#
  @# loop over the dimensions (in reverse order) closing the loops
  @#
  @for dimRep in reversed(field.inBasis(basis))
    @#
    @# If there isn't an indexOverride for this dimension, then reduce the indent and close the loop
    @if not dimRep.name in indexOverrides
      @set $indentLevel = indentLevel - 2
${dimRep.closeLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}@slurp
    @end if
    @#
    @if $dimRep.name in postDimensionLoopClosingCode
${postDimensionLoopClosingCode[dimRep.name], extraIndent=indentLevel}@slurp
    @end if
    @#
  @end for
  @#
  @# Undefine vector components that weren't in vectorOverrides
  @for vector in vectors
    @if vector in vectorOverrides or vector in vectorsNotNeedingDefines
      @continue
    @end if
    @for componentName in vector.components
#undef $componentName
    @end for
  @end for
  @# loop over geometry dimensions undefining dimension step variable names for those that
  @# aren't in this field, but are in any of the $vectors fields, unless we have an index override for it.
  @for $dimension in $geometry.dimensions
    @if $field.hasDimension($dimension)
      @continue
    @end if
    @#
    @if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0
      @continue
    @end if
    @#
    @set $dimRep = dimension.inBasis(basis)
    @if dimRep.name in indexOverrides
      @continue
    @end if
#undef d${dimRep.name}
  @end for
  @#
${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict)}@slurp
  @#
@end def


@def prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides)
@#doc: Insert prologue for dimension $dimension when its index variable has been overridden
  @#
  @# As this field contains this dimension, we must make sure that the indexOverride dictionary contains
  @# a value for this field
  @assert field in $indexOverrides[$dimRep.name]
  @#
unsigned long ${dimRep.loopIndex} = ${indexOverrides[dimRep.name][field]};
  @# loop over the vectors in field $field, because we need to fix up their index pointers
  @# and those vectors with the same dimensions
  @for $vector in [v for v in vectors if v.field.dimensions == field.dimensions]
_${vector.id}_index_pointer += ( 0@slurp
 ${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}@slurp
 ) * _${vector.id}_ncomponents;
  @end for

  @#
@end def


@def setExplicitIndexPointersForVectorsWithFieldAndBasis($vectors, $field, $basis, $indexOverrides)
@#doc: Set index pointers for those vectors requiring it to be set explicitly
  @#
  @# There's no need to (re-)set the index pointer for fields that have no dimensions
  @set $vectorsNeedingExplicitIndexPointers = [vector for vector in vectors if vector.field.dimensions]
  @if len(vectorsNeedingExplicitIndexPointers) == 0
    @return
  @end if
  @#
  @# For the vectors that are not in the field $field, set their index pointers
// Set index pointers explicitly for (some) vectors
  @for vector in vectorsNeedingExplicitIndexPointers
    @#
_${vector.id}_index_pointer = ( 0@slurp
    @for dimRep in vector.field.inBasis(basis)
${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}@slurp
    @end for
 ) * _${vector.id}_ncomponents;
  @end for
  @#
@end def

@def explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis($vector, $dimRep, $field, $basis, $indexOverrides)
  @#
  @# Blank line for output formatting

  @# Not all of the dimensions in the vector's field's dimensions will necessarily
  @# be in $field's dimensions, and we need to do slightly different things when they
  @# aren't in $field's dimensions.
  @#
  @# First, check the case that they both have this dimension
  @set fieldDimRepList = [dr for dr in field.inBasis(basis) if dr.name == dimRep.name]
  @#
  @if fieldDimRepList
    @# First, consider when they both contain this dimension
    @#
    @assert len(fieldDimRepList) == 1
    @set $fieldDimRep = fieldDimRepList[0]
    @#
    @# If the lattices are the same, then there is nothing special to be done for this dimension
    @# We also require that there are neither dimension could have a local offset
    @set $hasLocalOffset = dimRep.hasLocalOffset or fieldDimRep.hasLocalOffset
    @if dimRep.runtimeLattice == fieldDimRep.runtimeLattice and not hasLocalOffset
   + ${fieldDimRep.loopIndex}@slurp
 * $vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)@slurp
    @else
   + ( ${dimRep.localIndexFromIndexForDimensionRep(fieldDimRep)} )@slurp
 * $vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)@slurp
    @end if
  @else
    @# Now, consider when $field doesn't contain this dimension. If this dimension has an index override, then
    @# use the index pointers from that.
    @if dimRep.name in indexOverrides
      @# We do have an index override for this dimension
      @#
      @# Check that we actually have an entry for this vector's field
      @assert vector.field in indexOverrides[dimRep.name]
   + ${indexOverrides[dimRep.name][vector.field]}@slurp
  * $vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)@slurp
    @else
      @# We don't have an index override for this dimension.
      @# What happens in this case depends on whether or not the vector
      @# is in fourier space in this dimension. If it is, then we want to take its
      @# value at k=0 (the first element in this dimension). If it isn't in fourier
      @# space, then we want to take its element in the middle.
      @#
      @# Either way, this is handled by the dimension. But we can't have this dimension distributed.
      @assert not dimRep.hasLocalOffset, "Can't do single point samples with the distributed-mpi driver."
   + ( ${dimRep.indexForSinglePointSample} )@slurp
  * $vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)@slurp
    @end if
  @end if
  @#
@end def


@def epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis($vectorOverrides, $field, $basis)
@#doc: Integrate the overridden vectors
  @#
  @# Loop over the overridden vectors
  @for $vector in $vectorOverrides

    @# Determine which dimensions are being integrated over (if any)
    @# These are the ones that are in $field, but not in the vector's field
    @set $dimensionsIntegratedOver = [dim for dim in field.dimensions if not vector.field.hasDimension(dim)]
    @#
    @# Loop over the components in each vector
    @for $componentNumber, $componentName in enumerate($vector.components)
_active_${vector.id}[_${vector.id}_index_pointer + ${componentNumber}] += ${componentName}@slurp
      @# Loop over the dimensions
      @for $dimension in $dimensionsIntegratedOver
 * d${dimension.inBasis(basis).name}@slurp
      @end for
;
    @end for
  @end for
  @#
@end def


@def incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep($vectors, $field, $basis, $lastLoopDimRep)
@#doc: Increment index pointers but only for those in field `field` or in a field with the same dimensions.
  @#
  @# For the vectors that are in the field $field, increment their index pointers.
  @#
  @# If none of $vectors have field $field, then there's nothing to do
  @if len(vectors) == 0
    @return
  @end if
// Increment index pointers for vectors in field $field.name (or having the same dimensions)
  @for vector in vectors
    @# We can only do this for vectors in $field
    @# or that have the same dimensions
    @assert vector.field.dimensions == field.dimensions
    @#
    @# Now we need to increment the vector
    @# We need to know the last loop dimension because we could be looping over the second last dimension and not the last
    @# because the last was overridden by an indexOverride. Hence the step may not be _stuff_ncomponents,
    @# but _stuff_latticeN * _stuff_ncomponents (etc.)
    @# This is needed for cross-propagation when cross-propagating along the last dimension.
_${vector.id}_index_pointer += $field.localPointsInDimensionsAfterDimRepInBasis(lastLoopDimRep, basis) * _${vector.id}_ncomponents;
  @end for

  @#
@end def

@def evaluateComputedVectors($vectors, $static = True)
@*doc: 
Evaluate the computed vectors in an appropriate order taking into account dependencies.  
All noises vectors must have the same static/dynamic type as that passed in.
*@
  @#
  @for vector in self.evaluationOrderForVectors(vectors, static, predicate = lambda x: x.isComputed)
${vector.functions['evaluate'].call()}
  @end for
  @#
@end def

@def copyVectors($vectors, $destPrefix, $srcPrefix = None)
@#doc: Copy the contents of `vecSrc` into `vecDest`
  @#
  @for $vector in $vectors
memcpy(${destPrefix}_${vector.id}, ${srcPrefix}_${vector.id}, sizeof(${vector.type}) * ${vector.allocSize});
  @end for
  @#
@end def

@def swapVectorPointers($vectors, $destPrefix, $srcPrefix = None)
@#dex: Swap the pointers of `vecSrc` and `vecDest`
  @#
{
  @for $vector in $vectors
  ${vector.type}* _temp_${destPrefix}_${vector.id} = ${destPrefix}_${vector.id};
  ${destPrefix}_${vector.id} = ${srcPrefix}_${vector.id};
  ${srcPrefix}_${vector.id} = _temp_${destPrefix}_${vector.id};
  @end for
}
  @#
@end def

@def assignVectorPointers($vectors, $destPrefix, $srcPrefix = None)
@#dex: Assign the pointer of `vecSrc` to `vecDest`
  @#
  @for $vector in $vectors
${destPrefix}_${vector.id} = ${srcPrefix}_${vector.id};
  @end for
  @#
@end def