#!/usr/bin/env python3




##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
    import builtins as builtin
except ImportError:
    import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
from Cheetah.compat import unicode
from xpdeint._ScriptElement import _ScriptElement
from xpdeint.CallOnceGuards import callOnceGuard

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.1'
__CHEETAH_versionTuple__ = (3, 2, 1, 'final', 0)
__CHEETAH_genTime__ = 1556840495.594155
__CHEETAH_genTimestamp__ = 'Fri May  3 09:41:35 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.3.0/xpdeint/ScriptElement.tmpl'
__CHEETAH_srcLastModified__ = 'Thu Apr  4 16:29:24 2019'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'

if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
    raise AssertionError(
      'This template was compiled with Cheetah version'
      ' %s. Templates compiled before version %s must be recompiled.'%(
         __CHEETAH_version__, RequiredCheetahVersion))

##################################################
## CLASSES

class ScriptElement(_ScriptElement):
    """
    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.
    """

    ##################################################
    ## CHEETAH GENERATED METHODS


    def __init__(self, *args, **KWs):

        super(ScriptElement, self).__init__(*args, **KWs)
        if not self._CHEETAH__instanceInitialized:
            cheetahKWArgs = {}
            allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
            for k,v in KWs.items():
                if k in allowedKWs: cheetahKWArgs[k] = v
            self._initCheetahInstance(**cheetahKWArgs)
        

    def loopOverVectorsWithInnerContentTemplate(self, vectors, templateString, basis=None, **KWS):


        """
        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.
        """

        ## CHEETAH: generated from @def loopOverVectorsWithInnerContentTemplate($vectors, $templateString, $basis = None) at line 103, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        assert len(VFFSL(SL,"templateString",True)) > 0
        # 
        templateFeatureOrdering = ['AutoVectorise']
        dict = {'templateString': VFFSL(SL,"templateString",True),                'originalTemplateString': VFFSL(SL,"templateString",True),                'loopCountPrefixFunction': None,                'templateFunctions': []}
        VFFSL(SL,"insertCodeForFeatures",False)('loopOverVectorsWithInnerContentTemplateModifyTemplate',
                                 VFFSL(SL,"templateFeatureOrdering",True),
                                 VFFSL(SL,"dict",True))
        templateString = dict['templateString']
        #  If the loopCountPrefixFunction is None, then provide an empty default
        loopCountPrefixFunction = dict['loopCountPrefixFunction'] or (lambda v: '')
        # 
        #  The template string should end with a new line, if it doesn't we'll add it
        if VFFSL(SL,"templateString",True)[-1] != '\n': # generated from line 138, col 3
            templateString = VFFSL(SL,"templateString",True) + '\n'
        # 
        templateString += '\n'.join(dict['templateFunctions'])
        # 
        templateVariables = {'index': '_i0'}
        innerLoopTemplate = VFFSL(SL,"templateObjectFromStringWithTemplateVariables",False)(VFFSL(SL,"templateString",True), VFFSL(SL,"templateVariables",True))
        # 
        loopFeatureOrdering = ['AutoVectorise', 'OpenMP']
        VFFSL(SL,"dict",True)['extraIndent'] = 0
        VFFSL(SL,"dict",True)['template'] = VFFSL(SL,"innerLoopTemplate",True)
        for vector in VFFSL(SL,"vectors",True): # generated from line 150, col 3
            # 
            #  Get the loopCountPrefix from the loopCountPrefixFunction
            loopCountPrefix = VFFSL(SL,"loopCountPrefixFunction",False)(VFFSL(SL,"vector",True))
            # 
            #  Set the template's current vector
            VFFSL(SL,"templateVariables",True)['vector'] = VFFSL(SL,"vector",True)
            _v = VFFSL(SL,"insertCodeForFeatures",False)('loopOverVectorsWithInnerContentTemplateBegin', VFFSL(SL,"loopFeatureOrdering",True), VFFSL(SL,"dict",True)) # "${insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateBegin', $loopFeatureOrdering, $dict)}" on line 157, col 1
            if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateBegin', $loopFeatureOrdering, $dict)}")) # from line 157, col 1.
            ## START CAPTURE REGION: _57033238 loopString at line 158, col 5 in the source.
            _orig_trans_57033238 = trans
            _wasBuffering_57033238 = self._CHEETAH__isBuffering
            self._CHEETAH__isBuffering = True
            trans = _captureCollector_57033238 = DummyTransaction()
            write = _captureCollector_57033238.response().write
            if basis is None: # generated from line 159, col 7
                vectorSize = vector.allocSize
            else: # generated from line 161, col 7
                vectorSize = vector.sizeInBasis(basis)
            write('''for (long _i0 = 0; _i0 < ''')
            _v = VFFSL(SL,"loopCountPrefix",True) # '${loopCountPrefix}' on line 164, col 26
            if _v is not None: write(_filter(_v, rawExpr='${loopCountPrefix}')) # from line 164, col 26.
            _v = VFFSL(SL,"vectorSize",True) # '${vectorSize}' on line 164, col 44
            if _v is not None: write(_filter(_v, rawExpr='${vectorSize}')) # from line 164, col 44.
            write('''; _i0++) {
  ''')
            _v = VFFSL(SL,"innerLoopTemplate",True) # '${innerLoopTemplate, autoIndent=True}' on line 165, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${innerLoopTemplate, autoIndent=True}')) # from line 165, col 3.
            write('''}
''')
            trans = _orig_trans_57033238
            write = trans.response().write
            self._CHEETAH__isBuffering = _wasBuffering_57033238 
            loopString = _captureCollector_57033238.response().getvalue()
            del _orig_trans_57033238
            del _captureCollector_57033238
            del _wasBuffering_57033238
            _v = VFFSL(SL,"loopString",True) # "${loopString, extraIndent=dict['extraIndent']}" on line 168, col 1
            if _v is not None: write(_filter(_v, extraIndent=dict['extraIndent'], rawExpr="${loopString, extraIndent=dict['extraIndent']}")) # from line 168, col 1.
            write('''
''')
            _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverVectorsWithInnerContentTemplateEnd', VFFSL(SL,"loopFeatureOrdering",True), VFFSL(SL,"dict",True)) # "${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentTemplateEnd', $loopFeatureOrdering, $dict)}" on line 169, col 1
            if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentTemplateEnd', $loopFeatureOrdering, $dict)}")) # from line 169, col 1.
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def loopOverVectorsInBasisWithInnerContent(self, vectors, basis, innerContent, **KWS):


        """
        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.
        """

        ## CHEETAH: generated from @def loopOverVectorsInBasisWithInnerContent($vectors, $basis, $innerContent) at line 173, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        #  All of the vectors must be in the same field
        fields = set([v.field for v in VFFSL(SL,"vectors",True)])
        # 
        assert len(VFFSL(SL,"fields",True)) == 1
        field = VFFSL(SL,"anyObject",False)(VFFSL(SL,"fields",True))
        # 
        featureOrdering = ['OpenMP']
        # 
        blankLineSeparator = ''
        # 
        #  Initialise index pointers
        for vector in VFFSL(SL,"vectors",True): # generated from line 195, col 3
            #  Don't output a blank line for the first vector
            _v = VFFSL(SL,"blankLineSeparator",True) # '${blankLineSeparator}' on line 197, col 1
            if _v is not None: write(_filter(_v, rawExpr='${blankLineSeparator}')) # from line 197, col 1.
            blankLineSeparator = '\n'
            # 
            write('''long _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 200, col 7
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 200, col 7.
            write('''_index_pointer = 0;
''')
            # 
            for componentNumber, componentName in enumerate(VFFSL(SL,"vector.components",True)): # generated from line 202, col 5
                write('''#define ''')
                _v = VFFSL(SL,"componentName",True) # '$componentName' on line 203, col 9
                if _v is not None: write(_filter(_v, rawExpr='$componentName')) # from line 203, col 9.
                write(''' _active_''')
                _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 203, col 32
                if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 203, col 32.
                write('''[_''')
                _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 203, col 46
                if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 203, col 46.
                write('''_index_pointer + ''')
                _v = VFFSL(SL,"componentNumber",True) # '$componentNumber' on line 203, col 75
                if _v is not None: write(_filter(_v, rawExpr='$componentNumber')) # from line 203, col 75.
                write(''']
''')
        dict = {'vectors': VFFSL(SL,"vectors",True), 'loopCode': innerContent}
        _v = VFFSL(SL,"insertCodeForFeatures",False)('loopOverVectorsWithInnerContentBegin', VFFSL(SL,"featureOrdering",True), VFFSL(SL,"dict",True)) # "${insertCodeForFeatures('loopOverVectorsWithInnerContentBegin', $featureOrdering, $dict)}" on line 207, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('loopOverVectorsWithInnerContentBegin', $featureOrdering, $dict)}")) # from line 207, col 1.
        write('''for (long _i0 = 0; _i0 < ''')
        _v = VFN(VFFSL(SL,"field",True),"sizeInBasis",False)(basis) # '${field.sizeInBasis(basis)}' on line 208, col 26
        if _v is not None: write(_filter(_v, rawExpr='${field.sizeInBasis(basis)}')) # from line 208, col 26.
        write('''; _i0++) {
  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverVectorsWithInnerContentEnd', VFFSL(SL,"featureOrdering",True), VFFSL(SL,"dict",True)) # "${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentEnd', $featureOrdering, $dict), autoIndent=True}" on line 209, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentEnd', $featureOrdering, $dict), autoIndent=True}")) # from line 209, col 3.
        # 
        write('''  ''')
        _v = VFFSL(SL,"innerContent",True) # '${innerContent, autoIndent=True}' on line 211, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${innerContent, autoIndent=True}')) # from line 211, col 3.
        write('''
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 213, col 3
            write('''  _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 214, col 4
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 214, col 4.
            write('''_index_pointer += _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 214, col 35
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 214, col 35.
            write('''_ncomponents;
''')
        write('''}
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 217, col 3
            for componentName in VFFSL(SL,"vector.components",True): # generated from line 218, col 5
                write('''#undef ''')
                _v = VFFSL(SL,"componentName",True) # '$componentName' on line 219, col 8
                if _v is not None: write(_filter(_v, rawExpr='$componentName')) # from line 219, col 8.
                write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def loopOverFieldInBasisWithVectorsAndInnerContent(self, field, basis, vectors, innerLoopCode, indexOverrides=None, vectorOverrides=None, loopingOrder=_ScriptElement.LoopingOrder.MemoryOrder, preDimensionLoopOpeningCode=None, postDimensionLoopClosingCode=None, vectorsNotNeedingDefines=None, **KWS):


        """
        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.
        """

        ## CHEETAH: generated from @def loopOverFieldInBasisWithVectorsAndInnerContent($field, $basis, $vectors, $innerLoopCode, $indexOverrides = None, $vectorOverrides = None, $loopingOrder = _ScriptElement.LoopingOrder.MemoryOrder, $preDimensionLoopOpeningCode = None, $postDimensionLoopClosingCode = None, vectorsNotNeedingDefines = None) at line 225, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  Defaults
        # 
        indexOverrides = indexOverrides or {}
        vectorOverrides = vectorOverrides or []
        preDimensionLoopOpeningCode = preDimensionLoopOpeningCode or {}
        postDimensionLoopClosingCode = postDimensionLoopClosingCode or {}
        vectorsNotNeedingDefines = vectorsNotNeedingDefines or set()
        # 
        featureOrdering = ['Driver']
        featuresDict = { 'field': field,                         'basis': basis,                         'vectors': vectors,                         'indexOverrides': indexOverrides,                         'vectorOverrides': vectorOverrides,                         'preDimensionLoopOpeningCode': preDimensionLoopOpeningCode,                         'postDimensionLoopClosingCode': postDimensionLoopClosingCode,                       }
        _v = VFFSL(SL,"insertCodeForFeatures",False)('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict) # "${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict)}" on line 293, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict)}")) # from line 293, col 1.
        # 
        #  Some vectors will need to have their index pointers set explicitly.
        #  These will be those which belong to fields with different dimensions.
        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 VFFSL(SL,"loopingOrder",True) != VFFSL(SL,"LoopingOrder.MemoryOrder",True): # generated from line 301, col 3
            vectorsRequiringExplictIndexPointers.update(VFFSL(SL,"vectors",True))
        # 
        #  Now determine the vectors not requiring explicit index pointers
        vectorsNotRequiringExplicitIndexPointers = set(vectors).difference(vectorsRequiringExplictIndexPointers)
        # 
        indentLevel = 0
        # 
        #  Initialise index pointers
        for vector in VFFSL(SL,"vectors",True): # generated from line 311, col 3
            # 
            write('''long _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 313, col 7
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 313, col 7.
            write('''_index_pointer = 0;
''')
            if vector in vectorsNotNeedingDefines: # generated from line 314, col 5
                pass
            elif vector in vectorOverrides: # generated from line 316, col 5
                #  This vector is in vectorOverrides, so instead of #defining, we want to create variables
                for componentName in vector.components: # generated from line 318, col 7
                    _v = VFFSL(SL,"vector.type",True) # '$vector.type' on line 319, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$vector.type')) # from line 319, col 1.
                    write(''' ''')
                    _v = VFFSL(SL,"componentName",True) # '$componentName' on line 319, col 14
                    if _v is not None: write(_filter(_v, rawExpr='$componentName')) # from line 319, col 14.
                    write(''';
''')
            else: # generated from line 321, col 5
                #  If vector isn't in vectorOverrides or vectorsNotNeedingDefines, then we want to #define the vector's components
                for componentNumber, componentName in enumerate(VFFSL(SL,"vector.components",True)): # generated from line 323, col 7
                    write('''#define ''')
                    _v = VFFSL(SL,"componentName",True) # '$componentName' on line 324, col 9
                    if _v is not None: write(_filter(_v, rawExpr='$componentName')) # from line 324, col 9.
                    write(''' _active_''')
                    _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 324, col 32
                    if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 324, col 32.
                    write('''[_''')
                    _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 324, col 46
                    if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 324, col 46.
                    write('''_index_pointer + ''')
                    _v = VFFSL(SL,"componentNumber",True) # '$componentNumber' on line 324, col 75
                    if _v is not None: write(_filter(_v, rawExpr='$componentNumber')) # from line 324, col 75.
                    write(''']
''')
        #  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 VFFSL(SL,"geometry.dimensions",True): # generated from line 330, col 3
            if VFN(VFFSL(SL,"field",True),"hasDimension",False)(VFFSL(SL,"dimension",True)): # generated from line 331, col 5
                continue
            # 
            if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0: # generated from line 335, col 5
                continue
            # 
            dimRep = dimension.inBasis(basis)
            if dimRep.name in indexOverrides: # generated from line 340, col 5
                continue
            write('''
''')
            _v = VFFSL(SL,"dimRep.createCoordinateVariableForSinglePointSample",True) # '${dimRep.createCoordinateVariableForSinglePointSample}' on line 344, col 1
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.createCoordinateVariableForSinglePointSample}')) # from line 344, col 1.
            write('''
''')
        # 
        #  loop over the dimensions opening the loops
        lastLoopDimRep = None
        for dimRep in field.inBasis(basis): # generated from line 350, col 3
            # 
            if dimRep.name in preDimensionLoopOpeningCode: # generated from line 352, col 5
                _v = VFFSL(SL,"preDimensionLoopOpeningCode",True)[VFFSL(SL,"dimRep.name",True)] # '${preDimensionLoopOpeningCode[$dimRep.name], extraIndent=$indentLevel}' on line 353, col 1
                if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr='${preDimensionLoopOpeningCode[$dimRep.name], extraIndent=$indentLevel}')) # from line 353, col 1.
            if not dimRep.name in indexOverrides: # generated from line 355, col 5
                #  If there isn't an indexOverride for this dimension, then open a loop
                lastLoopDimRep = dimRep
                # 
                loopOpeningFeatureOrdering = ['OpenMP']
                featuresDict.update({        'vectorsNotRequiringExplicitIndexPointers': vectorsNotRequiringExplicitIndexPointers,        'dimRep': dimRep,        'loopCode': innerLoopCode      })
                _v = VFFSL(SL,"insertCodeForFeatures",False)('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict) # "${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}" on line 365, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr="${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}")) # from line 365, col 1.
                # 
                _v = VFN(VFFSL(SL,"dimRep",True),"openLoop",False)(loopingOrder=loopingOrder) # '${dimRep.openLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}' on line 367, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${dimRep.openLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}')) # from line 367, col 1.
                indentLevel = VFFSL(SL,"indentLevel",True) + 2
                _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict) # "${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}" on line 369, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr="${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}")) # from line 369, col 1.
            else: # generated from line 370, col 5
                #  We have an indexOverride for this dimension. 
                _v = VFFSL(SL,"prologueForOverriddenDimRepInFieldInBasisWithVectors",False)(VFFSL(SL,"dimRep",True), VFFSL(SL,"field",True), VFFSL(SL,"basis",True), VFFSL(SL,"vectors",True), VFFSL(SL,"indexOverrides",True)) # '${prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides), extraIndent=$indentLevel}' on line 372, col 1
                if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr='${prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides), extraIndent=$indentLevel}')) # from line 372, col 1.
            # 
        # 
        result = VFFSL(SL,"setExplicitIndexPointersForVectorsWithFieldAndBasis",False)(vectorsRequiringExplictIndexPointers, field, basis, indexOverrides)
        if result: # generated from line 378, col 3
            _v = VFFSL(SL,"result",True) # '${result, extraIndent=indentLevel}' on line 379, col 1
            if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${result, extraIndent=indentLevel}')) # from line 379, col 1.
        # 
        _v = VFFSL(SL,"innerLoopCode",True) # '${innerLoopCode, extraIndent=$indentLevel}' on line 382, col 1
        if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr='${innerLoopCode, extraIndent=$indentLevel}')) # from line 382, col 1.
        _v = VFFSL(SL,"epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis",False)(vectorOverrides, field, basis) # '${epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(vectorOverrides, field, basis), extraIndent=indentLevel}' on line 383, col 1
        if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(vectorOverrides, field, basis), extraIndent=indentLevel}')) # from line 383, col 1.
        # 
        if lastLoopDimRep: # generated from line 385, col 3
            #  Increment the index pointers. This needs to be in a function in order to be able
            #  to use the variable indentation required
            _v = VFFSL(SL,"incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep",False)(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep) # '${incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep), extraIndent=indentLevel}' on line 388, col 1
            if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep), extraIndent=indentLevel}')) # from line 388, col 1.
        # 
        #  loop over the dimensions (in reverse order) closing the loops
        # 
        for dimRep in reversed(field.inBasis(basis)): # generated from line 393, col 3
            # 
            #  If there isn't an indexOverride for this dimension, then reduce the indent and close the loop
            if not dimRep.name in indexOverrides: # generated from line 396, col 5
                indentLevel = indentLevel - 2
                _v = VFN(VFFSL(SL,"dimRep",True),"closeLoop",False)(loopingOrder=loopingOrder) # '${dimRep.closeLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}' on line 398, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${dimRep.closeLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}')) # from line 398, col 1.
            # 
            if VFFSL(SL,"dimRep.name",True) in postDimensionLoopClosingCode: # generated from line 401, col 5
                _v = VFFSL(SL,"postDimensionLoopClosingCode",True)[dimRep.name] # '${postDimensionLoopClosingCode[dimRep.name], extraIndent=indentLevel}' on line 402, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr='${postDimensionLoopClosingCode[dimRep.name], extraIndent=indentLevel}')) # from line 402, col 1.
            # 
        # 
        #  Undefine vector components that weren't in vectorOverrides
        for vector in vectors: # generated from line 408, col 3
            if vector in vectorOverrides or vector in vectorsNotNeedingDefines: # generated from line 409, col 5
                continue
            for componentName in vector.components: # generated from line 412, col 5
                write('''#undef ''')
                _v = VFFSL(SL,"componentName",True) # '$componentName' on line 413, col 8
                if _v is not None: write(_filter(_v, rawExpr='$componentName')) # from line 413, col 8.
                write('''
''')
        #  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 VFFSL(SL,"geometry.dimensions",True): # generated from line 418, col 3
            if VFN(VFFSL(SL,"field",True),"hasDimension",False)(VFFSL(SL,"dimension",True)): # generated from line 419, col 5
                continue
            # 
            if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0: # generated from line 423, col 5
                continue
            # 
            dimRep = dimension.inBasis(basis)
            if dimRep.name in indexOverrides: # generated from line 428, col 5
                continue
            write('''#undef d''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 431, col 9
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 431, col 9.
            write('''
''')
        # 
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict) # "${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict)}" on line 434, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict)}")) # from line 434, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def prologueForOverriddenDimRepInFieldInBasisWithVectors(self, dimRep, field, basis, vectors, indexOverrides, **KWS):


        """
        Insert prologue for dimension $dimension when its index variable has been overridden
        """

        ## CHEETAH: generated from @def prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides) at line 439, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  As this field contains this dimension, we must make sure that the indexOverride dictionary contains
        #  a value for this field
        assert field in VFFSL(SL,"indexOverrides",True)[VFFSL(SL,"dimRep.name",True)]
        # 
        write('''unsigned long ''')
        _v = VFFSL(SL,"dimRep.loopIndex",True) # '${dimRep.loopIndex}' on line 446, col 15
        if _v is not None: write(_filter(_v, rawExpr='${dimRep.loopIndex}')) # from line 446, col 15.
        write(''' = ''')
        _v = VFFSL(SL,"indexOverrides",True)[dimRep.name][field] # '${indexOverrides[dimRep.name][field]}' on line 446, col 37
        if _v is not None: write(_filter(_v, rawExpr='${indexOverrides[dimRep.name][field]}')) # from line 446, col 37.
        write(''';
''')
        #  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]: # generated from line 449, col 3
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 450, col 2
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 450, col 2.
            write('''_index_pointer += ( 0''')
            write(''' ''')
            _v = VFFSL(SL,"explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis",False)(vector, dimRep, field, basis, indexOverrides) # '${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}' on line 451, col 2
            if _v is not None: write(_filter(_v, rawExpr='${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}')) # from line 451, col 2.
            write(''' ) * _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 452, col 7
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 452, col 7.
            write('''_ncomponents;
''')
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def setExplicitIndexPointersForVectorsWithFieldAndBasis(self, vectors, field, basis, indexOverrides, **KWS):


        """
        Set index pointers for those vectors requiring it to be set explicitly
        """

        ## CHEETAH: generated from @def setExplicitIndexPointersForVectorsWithFieldAndBasis($vectors, $field, $basis, $indexOverrides) at line 459, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  There's no need to (re-)set the index pointer for fields that have no dimensions
        vectorsNeedingExplicitIndexPointers = [vector for vector in vectors if vector.field.dimensions]
        if len(vectorsNeedingExplicitIndexPointers) == 0: # generated from line 464, col 3
            return
        # 
        #  For the vectors that are not in the field $field, set their index pointers
        write('''// Set index pointers explicitly for (some) vectors
''')
        for vector in vectorsNeedingExplicitIndexPointers: # generated from line 470, col 3
            # 
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 472, col 2
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 472, col 2.
            write('''_index_pointer = ( 0''')
            for dimRep in vector.field.inBasis(basis): # generated from line 473, col 5
                _v = VFFSL(SL,"explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis",False)(vector, dimRep, field, basis, indexOverrides) # '${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}' on line 474, col 1
                if _v is not None: write(_filter(_v, rawExpr='${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}')) # from line 474, col 1.
            write(''' ) * _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 476, col 7
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 476, col 7.
            write('''_ncomponents;
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(self, vector, dimRep, field, basis, indexOverrides, **KWS):



        ## CHEETAH: generated from @def explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis($vector, $dimRep, $field, $basis, $indexOverrides) at line 481, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  Blank line for output formatting
        write('''
''')
        #  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
        fieldDimRepList = [dr for dr in field.inBasis(basis) if dr.name == dimRep.name]
        # 
        if fieldDimRepList: # generated from line 492, col 3
            #  First, consider when they both contain this dimension
            # 
            assert len(fieldDimRepList) == 1
            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
            hasLocalOffset = dimRep.hasLocalOffset or fieldDimRep.hasLocalOffset
            if dimRep.runtimeLattice == fieldDimRep.runtimeLattice and not hasLocalOffset: # generated from line 501, col 5
                write('''   + ''')
                _v = VFFSL(SL,"fieldDimRep.loopIndex",True) # '${fieldDimRep.loopIndex}' on line 502, col 6
                if _v is not None: write(_filter(_v, rawExpr='${fieldDimRep.loopIndex}')) # from line 502, col 6.
                write(''' * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # '$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 503, col 4
                if _v is not None: write(_filter(_v, rawExpr='$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 503, col 4.
            else: # generated from line 504, col 5
                write('''   + ( ''')
                _v = VFN(VFFSL(SL,"dimRep",True),"localIndexFromIndexForDimensionRep",False)(fieldDimRep) # '${dimRep.localIndexFromIndexForDimensionRep(fieldDimRep)}' on line 505, col 8
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.localIndexFromIndexForDimensionRep(fieldDimRep)}')) # from line 505, col 8.
                write(''' )''')
                write(''' * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # '$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 506, col 4
                if _v is not None: write(_filter(_v, rawExpr='$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 506, col 4.
        else: # generated from line 508, col 3
            #  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: # generated from line 511, col 5
                #  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]
                write('''   + ''')
                _v = VFFSL(SL,"indexOverrides",True)[dimRep.name][vector.field] # '${indexOverrides[dimRep.name][vector.field]}' on line 516, col 6
                if _v is not None: write(_filter(_v, rawExpr='${indexOverrides[dimRep.name][vector.field]}')) # from line 516, col 6.
                write('''  * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # '$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 517, col 5
                if _v is not None: write(_filter(_v, rawExpr='$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 517, col 5.
            else: # generated from line 518, col 5
                #  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."
                write('''   + ( ''')
                _v = VFFSL(SL,"dimRep.indexForSinglePointSample",True) # '${dimRep.indexForSinglePointSample}' on line 527, col 8
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.indexForSinglePointSample}')) # from line 527, col 8.
                write(''' )''')
                write('''  * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # '$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 528, col 5
                if _v is not None: write(_filter(_v, rawExpr='$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 528, col 5.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(self, vectorOverrides, field, basis, **KWS):


        """
        Integrate the overridden vectors
        """

        ## CHEETAH: generated from @def epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis($vectorOverrides, $field, $basis) at line 535, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  Loop over the overridden vectors
        for vector in VFFSL(SL,"vectorOverrides",True): # generated from line 539, col 3
            write('''
''')
            #  Determine which dimensions are being integrated over (if any)
            #  These are the ones that are in $field, but not in the vector's field
            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(VFFSL(SL,"vector.components",True)): # generated from line 546, col 5
                write('''_active_''')
                _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 547, col 9
                if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 547, col 9.
                write('''[_''')
                _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 547, col 23
                if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 547, col 23.
                write('''_index_pointer + ''')
                _v = VFFSL(SL,"componentNumber",True) # '${componentNumber}' on line 547, col 52
                if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 547, col 52.
                write('''] += ''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 547, col 75
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 547, col 75.
                #  Loop over the dimensions
                for dimension in VFFSL(SL,"dimensionsIntegratedOver",True): # generated from line 549, col 7
                    write(''' * d''')
                    _v = VFN(VFN(VFFSL(SL,"dimension",True),"inBasis",False)(basis),"name",True) # '${dimension.inBasis(basis).name}' on line 550, col 5
                    if _v is not None: write(_filter(_v, rawExpr='${dimension.inBasis(basis).name}')) # from line 550, col 5.
                write(''';
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(self, vectors, field, basis, lastLoopDimRep, **KWS):


        """
        Increment index pointers but only for those in field `field` or in a field with the same dimensions.
        """

        ## CHEETAH: generated from @def incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep($vectors, $field, $basis, $lastLoopDimRep) at line 559, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        #  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: # generated from line 565, col 3
            return
        write('''// Increment index pointers for vectors in field ''')
        _v = VFFSL(SL,"field.name",True) # '$field.name' on line 568, col 50
        if _v is not None: write(_filter(_v, rawExpr='$field.name')) # from line 568, col 50.
        write(''' (or having the same dimensions)
''')
        for vector in vectors: # generated from line 569, col 3
            #  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.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 579, col 2
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 579, col 2.
            write('''_index_pointer += ''')
            _v = VFN(VFFSL(SL,"field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(lastLoopDimRep, basis) # '$field.localPointsInDimensionsAfterDimRepInBasis(lastLoopDimRep, basis)' on line 579, col 32
            if _v is not None: write(_filter(_v, rawExpr='$field.localPointsInDimensionsAfterDimRepInBasis(lastLoopDimRep, basis)')) # from line 579, col 32.
            write(''' * _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 579, col 107
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 579, col 107.
            write('''_ncomponents;
''')
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def evaluateComputedVectors(self, vectors, static=True, **KWS):


        """
        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.
        """

        ## CHEETAH: generated from @def evaluateComputedVectors($vectors, $static = True) at line 585, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        for vector in self.evaluationOrderForVectors(vectors, static, predicate = lambda x: x.isComputed): # generated from line 591, col 3
            _v = VFN(VFN(VFFSL(SL,"vector",True),"functions",True)['evaluate'],"call",False)() # "${vector.functions['evaluate'].call()}" on line 592, col 1
            if _v is not None: write(_filter(_v, rawExpr="${vector.functions['evaluate'].call()}")) # from line 592, col 1.
            write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def copyVectors(self, vectors, destPrefix, srcPrefix=None, **KWS):


        """
        Copy the contents of `vecSrc` into `vecDest`
        """

        ## CHEETAH: generated from @def copyVectors($vectors, $destPrefix, $srcPrefix = None) at line 597, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        for vector in VFFSL(SL,"vectors",True): # generated from line 600, col 3
            write('''memcpy(''')
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 601, col 8
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 601, col 8.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 601, col 22
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 601, col 22.
            write(''', ''')
            _v = VFFSL(SL,"srcPrefix",True) # '${srcPrefix}' on line 601, col 36
            if _v is not None: write(_filter(_v, rawExpr='${srcPrefix}')) # from line 601, col 36.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 601, col 49
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 601, col 49.
            write(''', sizeof(''')
            _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 601, col 70
            if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 601, col 70.
            write(''') * ''')
            _v = VFFSL(SL,"vector.allocSize",True) # '${vector.allocSize}' on line 601, col 88
            if _v is not None: write(_filter(_v, rawExpr='${vector.allocSize}')) # from line 601, col 88.
            write(''');
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def swapVectorPointers(self, vectors, destPrefix, srcPrefix=None, **KWS):



        ## CHEETAH: generated from @def swapVectorPointers($vectors, $destPrefix, $srcPrefix = None) at line 606, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # dex: Swap the pointers of `vecSrc` and `vecDest`
        # 
        write('''{
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 610, col 3
            write('''  ''')
            _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 611, col 3
            if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 611, col 3.
            write('''* _temp_''')
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 611, col 25
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 611, col 25.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 611, col 39
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 611, col 39.
            write(''' = ''')
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 611, col 54
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 611, col 54.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 611, col 68
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 611, col 68.
            write(''';
  ''')
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 612, col 3
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 612, col 3.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 612, col 17
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 612, col 17.
            write(''' = ''')
            _v = VFFSL(SL,"srcPrefix",True) # '${srcPrefix}' on line 612, col 32
            if _v is not None: write(_filter(_v, rawExpr='${srcPrefix}')) # from line 612, col 32.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 612, col 45
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 612, col 45.
            write(''';
  ''')
            _v = VFFSL(SL,"srcPrefix",True) # '${srcPrefix}' on line 613, col 3
            if _v is not None: write(_filter(_v, rawExpr='${srcPrefix}')) # from line 613, col 3.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 613, col 16
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 613, col 16.
            write(''' = _temp_''')
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 613, col 37
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 613, col 37.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 613, col 51
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 613, col 51.
            write(''';
''')
        write('''}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def assignVectorPointers(self, vectors, destPrefix, srcPrefix=None, **KWS):



        ## CHEETAH: generated from @def assignVectorPointers($vectors, $destPrefix, $srcPrefix = None) at line 619, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # dex: Assign the pointer of `vecSrc` to `vecDest`
        # 
        for vector in VFFSL(SL,"vectors",True): # generated from line 622, col 3
            _v = VFFSL(SL,"destPrefix",True) # '${destPrefix}' on line 623, col 1
            if _v is not None: write(_filter(_v, rawExpr='${destPrefix}')) # from line 623, col 1.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 623, col 15
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 623, col 15.
            write(''' = ''')
            _v = VFFSL(SL,"srcPrefix",True) # '${srcPrefix}' on line 623, col 30
            if _v is not None: write(_filter(_v, rawExpr='${srcPrefix}')) # from line 623, col 30.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 623, col 43
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 623, col 43.
            write(''';
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def writeBody(self, **KWS):



        ## CHEETAH: main method generated for this template
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        write('''
''')
        # 
        # 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/>.
        # 
        write('''



















''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        
    ##################################################
    ## CHEETAH GENERATED ATTRIBUTES


    _CHEETAH__instanceInitialized = False

    _CHEETAH_version = __CHEETAH_version__

    _CHEETAH_versionTuple = __CHEETAH_versionTuple__

    _CHEETAH_genTime = __CHEETAH_genTime__

    _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__

    _CHEETAH_src = __CHEETAH_src__

    _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__

    _mainCheetahMethod_for_ScriptElement = 'writeBody'

## END CLASS DEFINITION

if not hasattr(ScriptElement, '_initCheetahAttributes'):
    templateAPIClass = getattr(ScriptElement,
                               '_CHEETAH_templateClass',
                               Template)
    templateAPIClass._addCheetahPlumbingCodeToClass(ScriptElement)


# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://cheetahtemplate.org/

##################################################
## if run from command line:
if __name__ == '__main__':
    from Cheetah.TemplateCmdLineIface import CmdLineIface
    CmdLineIface(templateObj=ScriptElement()).run()


