@*
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 indexOverrides.has_key(dimRep.name)
      @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 indexOverrides.has_key(dimRep.name)
      @# 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 indexOverrides.has_key(dimRep.name)
      @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 indexOverrides.has_key(dimRep.name)
      @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 $indexOverrides[$dimRep.name].has_key(field)
  @#
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 += ${dimRep.loopIndex}@slurp
 * ${field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)};
  @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 indexOverrides.has_key(dimRep.name)
      @# We do have an index override for this dimension
      @#
      @# Check that we actually have an entry for this vector's field
      @assert indexOverrides[dimRep.name].has_key(vector.field)
   + ${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

