#!/usr/bin/env python




##################################################
## 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 xpdeint._ScriptElement import _ScriptElement
from xpdeint.CallOnceGuards import callOnceGuard

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1484975072.447894
__CHEETAH_genTimestamp__ = 'Sat Jan 21 16:04:32 2017'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.2.3/xpdeint/ScriptElement.tmpl'
__CHEETAH_srcLastModified__ = 'Sat Apr 11 14:05:45 2015'
__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 101, 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 136, 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 148, 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)) # u"${insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateBegin', $loopFeatureOrdering, $dict)}" on line 155, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('loopOverVectorsWithInnerContentTemplateBegin', $loopFeatureOrdering, $dict)}")) # from line 155, col 1.
            ## START CAPTURE REGION: _27522821 loopString at line 156, col 5 in the source.
            _orig_trans_27522821 = trans
            _wasBuffering_27522821 = self._CHEETAH__isBuffering
            self._CHEETAH__isBuffering = True
            trans = _captureCollector_27522821 = DummyTransaction()
            write = _captureCollector_27522821.response().write
            if basis is None: # generated from line 157, col 7
                vectorSize = vector.allocSize
            else: # generated from line 159, col 7
                vectorSize = vector.sizeInBasis(basis)
            write(u'''for (long _i0 = 0; _i0 < ''')
            _v = VFFSL(SL,"loopCountPrefix",True) # u'${loopCountPrefix}' on line 162, col 26
            if _v is not None: write(_filter(_v, rawExpr=u'${loopCountPrefix}')) # from line 162, col 26.
            _v = VFFSL(SL,"vectorSize",True) # u'${vectorSize}' on line 162, col 44
            if _v is not None: write(_filter(_v, rawExpr=u'${vectorSize}')) # from line 162, col 44.
            write(u'''; _i0++) {
  ''')
            _v = VFFSL(SL,"innerLoopTemplate",True) # u'${innerLoopTemplate, autoIndent=True}' on line 163, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${innerLoopTemplate, autoIndent=True}')) # from line 163, col 3.
            write(u'''}
''')
            trans = _orig_trans_27522821
            write = trans.response().write
            self._CHEETAH__isBuffering = _wasBuffering_27522821 
            loopString = _captureCollector_27522821.response().getvalue()
            del _orig_trans_27522821
            del _captureCollector_27522821
            del _wasBuffering_27522821
            _v = VFFSL(SL,"loopString",True) # u"${loopString, extraIndent=dict['extraIndent']}" on line 166, col 1
            if _v is not None: write(_filter(_v, extraIndent=dict['extraIndent'], rawExpr=u"${loopString, extraIndent=dict['extraIndent']}")) # from line 166, col 1.
            write(u'''
''')
            _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverVectorsWithInnerContentTemplateEnd', VFFSL(SL,"loopFeatureOrdering",True), VFFSL(SL,"dict",True)) # u"${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentTemplateEnd', $loopFeatureOrdering, $dict)}" on line 167, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentTemplateEnd', $loopFeatureOrdering, $dict)}")) # from line 167, 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 171, 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 193, col 3
            #  Don't output a blank line for the first vector
            _v = VFFSL(SL,"blankLineSeparator",True) # u'${blankLineSeparator}' on line 195, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${blankLineSeparator}')) # from line 195, col 1.
            blankLineSeparator = '\n'
            # 
            write(u'''long _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 198, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 198, col 7.
            write(u'''_index_pointer = 0;
''')
            # 
            for componentNumber, componentName in enumerate(VFFSL(SL,"vector.components",True)): # generated from line 200, col 5
                write(u'''#define ''')
                _v = VFFSL(SL,"componentName",True) # u'$componentName' on line 201, col 9
                if _v is not None: write(_filter(_v, rawExpr=u'$componentName')) # from line 201, col 9.
                write(u''' _active_''')
                _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 201, col 32
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 201, col 32.
                write(u'''[_''')
                _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 201, col 46
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 201, col 46.
                write(u'''_index_pointer + ''')
                _v = VFFSL(SL,"componentNumber",True) # u'$componentNumber' on line 201, col 75
                if _v is not None: write(_filter(_v, rawExpr=u'$componentNumber')) # from line 201, col 75.
                write(u''']
''')
        dict = {'vectors': VFFSL(SL,"vectors",True), 'loopCode': innerContent}
        _v = VFFSL(SL,"insertCodeForFeatures",False)('loopOverVectorsWithInnerContentBegin', VFFSL(SL,"featureOrdering",True), VFFSL(SL,"dict",True)) # u"${insertCodeForFeatures('loopOverVectorsWithInnerContentBegin', $featureOrdering, $dict)}" on line 205, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('loopOverVectorsWithInnerContentBegin', $featureOrdering, $dict)}")) # from line 205, col 1.
        write(u'''for (long _i0 = 0; _i0 < ''')
        _v = VFN(VFFSL(SL,"field",True),"sizeInBasis",False)(basis) # u'${field.sizeInBasis(basis)}' on line 206, col 26
        if _v is not None: write(_filter(_v, rawExpr=u'${field.sizeInBasis(basis)}')) # from line 206, col 26.
        write(u'''; _i0++) {
  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverVectorsWithInnerContentEnd', VFFSL(SL,"featureOrdering",True), VFFSL(SL,"dict",True)) # u"${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentEnd', $featureOrdering, $dict), autoIndent=True}" on line 207, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeaturesInReverseOrder('loopOverVectorsWithInnerContentEnd', $featureOrdering, $dict), autoIndent=True}")) # from line 207, col 3.
        # 
        write(u'''  ''')
        _v = VFFSL(SL,"innerContent",True) # u'${innerContent, autoIndent=True}' on line 209, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${innerContent, autoIndent=True}')) # from line 209, col 3.
        write(u'''
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 211, col 3
            write(u'''  _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 212, col 4
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 212, col 4.
            write(u'''_index_pointer += _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 212, col 35
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 212, col 35.
            write(u'''_ncomponents;
''')
        write(u'''}
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 215, col 3
            for componentName in VFFSL(SL,"vector.components",True): # generated from line 216, col 5
                write(u'''#undef ''')
                _v = VFFSL(SL,"componentName",True) # u'$componentName' on line 217, col 8
                if _v is not None: write(_filter(_v, rawExpr=u'$componentName')) # from line 217, col 8.
                write(u'''
''')
        # 
        
        ########################################
        ## 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 223, 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) # u"${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict)}" on line 291, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentBegin', featureOrdering, featuresDict)}")) # from line 291, 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 299, 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 309, col 3
            # 
            write(u'''long _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 311, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 311, col 7.
            write(u'''_index_pointer = 0;
''')
            if vector in vectorsNotNeedingDefines: # generated from line 312, col 5
                pass
            elif vector in vectorOverrides: # generated from line 314, col 5
                #  This vector is in vectorOverrides, so instead of #defining, we want to create variables
                for componentName in vector.components: # generated from line 316, col 7
                    _v = VFFSL(SL,"vector.type",True) # u'$vector.type' on line 317, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$vector.type')) # from line 317, col 1.
                    write(u''' ''')
                    _v = VFFSL(SL,"componentName",True) # u'$componentName' on line 317, col 14
                    if _v is not None: write(_filter(_v, rawExpr=u'$componentName')) # from line 317, col 14.
                    write(u''';
''')
            else: # generated from line 319, 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 321, col 7
                    write(u'''#define ''')
                    _v = VFFSL(SL,"componentName",True) # u'$componentName' on line 322, col 9
                    if _v is not None: write(_filter(_v, rawExpr=u'$componentName')) # from line 322, col 9.
                    write(u''' _active_''')
                    _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 322, col 32
                    if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 322, col 32.
                    write(u'''[_''')
                    _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 322, col 46
                    if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 322, col 46.
                    write(u'''_index_pointer + ''')
                    _v = VFFSL(SL,"componentNumber",True) # u'$componentNumber' on line 322, col 75
                    if _v is not None: write(_filter(_v, rawExpr=u'$componentNumber')) # from line 322, col 75.
                    write(u''']
''')
        #  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 328, col 3
            if VFN(VFFSL(SL,"field",True),"hasDimension",False)(VFFSL(SL,"dimension",True)): # generated from line 329, col 5
                continue
            # 
            if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0: # generated from line 333, col 5
                continue
            # 
            dimRep = dimension.inBasis(basis)
            if indexOverrides.has_key(dimRep.name): # generated from line 338, col 5
                continue
            write(u'''
''')
            _v = VFFSL(SL,"dimRep.createCoordinateVariableForSinglePointSample",True) # u'${dimRep.createCoordinateVariableForSinglePointSample}' on line 342, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.createCoordinateVariableForSinglePointSample}')) # from line 342, col 1.
            write(u'''
''')
        # 
        #  loop over the dimensions opening the loops
        lastLoopDimRep = None
        for dimRep in field.inBasis(basis): # generated from line 348, col 3
            # 
            if dimRep.name in preDimensionLoopOpeningCode: # generated from line 350, col 5
                _v = VFFSL(SL,"preDimensionLoopOpeningCode",True)[VFFSL(SL,"dimRep.name",True)] # u'${preDimensionLoopOpeningCode[$dimRep.name], extraIndent=$indentLevel}' on line 351, col 1
                if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr=u'${preDimensionLoopOpeningCode[$dimRep.name], extraIndent=$indentLevel}')) # from line 351, col 1.
            if not indexOverrides.has_key(dimRep.name): # generated from line 353, 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) # u"${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}" on line 363, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u"${insertCodeForFeatures('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenBegin', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}")) # from line 363, col 1.
                # 
                _v = VFN(VFFSL(SL,"dimRep",True),"openLoop",False)(loopingOrder=loopingOrder) # u'${dimRep.openLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}' on line 365, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${dimRep.openLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}')) # from line 365, col 1.
                indentLevel = VFFSL(SL,"indentLevel",True) + 2
                _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict) # u"${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}" on line 367, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u"${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentLoopOpenEnd', loopOpeningFeatureOrdering, featuresDict), extraIndent=indentLevel}")) # from line 367, col 1.
            else: # generated from line 368, 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)) # u'${prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides), extraIndent=$indentLevel}' on line 370, col 1
                if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr=u'${prologueForOverriddenDimRepInFieldInBasisWithVectors($dimRep, $field, $basis, $vectors, $indexOverrides), extraIndent=$indentLevel}')) # from line 370, col 1.
            # 
        # 
        result = VFFSL(SL,"setExplicitIndexPointersForVectorsWithFieldAndBasis",False)(vectorsRequiringExplictIndexPointers, field, basis, indexOverrides)
        if result: # generated from line 376, col 3
            _v = VFFSL(SL,"result",True) # u'${result, extraIndent=indentLevel}' on line 377, col 1
            if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${result, extraIndent=indentLevel}')) # from line 377, col 1.
        # 
        _v = VFFSL(SL,"innerLoopCode",True) # u'${innerLoopCode, extraIndent=$indentLevel}' on line 380, col 1
        if _v is not None: write(_filter(_v, extraIndent=VFFSL(SL,"indentLevel",True), rawExpr=u'${innerLoopCode, extraIndent=$indentLevel}')) # from line 380, col 1.
        _v = VFFSL(SL,"epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis",False)(vectorOverrides, field, basis) # u'${epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(vectorOverrides, field, basis), extraIndent=indentLevel}' on line 381, col 1
        if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${epilogueToIntegrateOverriddenVectorsForSamplingFieldInBasis(vectorOverrides, field, basis), extraIndent=indentLevel}')) # from line 381, col 1.
        # 
        if lastLoopDimRep: # generated from line 383, 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) # u'${incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep), extraIndent=indentLevel}' on line 386, col 1
            if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${incrementIndexPointersForVectorsWithFieldBasisAndLastLoopDimRep(vectorsNotRequiringExplicitIndexPointers, field, basis, lastLoopDimRep), extraIndent=indentLevel}')) # from line 386, col 1.
        # 
        #  loop over the dimensions (in reverse order) closing the loops
        # 
        for dimRep in reversed(field.inBasis(basis)): # generated from line 391, col 3
            # 
            #  If there isn't an indexOverride for this dimension, then reduce the indent and close the loop
            if not indexOverrides.has_key(dimRep.name): # generated from line 394, col 5
                indentLevel = indentLevel - 2
                _v = VFN(VFFSL(SL,"dimRep",True),"closeLoop",False)(loopingOrder=loopingOrder) # u'${dimRep.closeLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}' on line 396, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${dimRep.closeLoop(loopingOrder=loopingOrder), extraIndent=indentLevel}')) # from line 396, col 1.
            # 
            if VFFSL(SL,"dimRep.name",True) in postDimensionLoopClosingCode: # generated from line 399, col 5
                _v = VFFSL(SL,"postDimensionLoopClosingCode",True)[dimRep.name] # u'${postDimensionLoopClosingCode[dimRep.name], extraIndent=indentLevel}' on line 400, col 1
                if _v is not None: write(_filter(_v, extraIndent=indentLevel, rawExpr=u'${postDimensionLoopClosingCode[dimRep.name], extraIndent=indentLevel}')) # from line 400, col 1.
            # 
        # 
        #  Undefine vector components that weren't in vectorOverrides
        for vector in vectors: # generated from line 406, col 3
            if vector in vectorOverrides or vector in vectorsNotNeedingDefines: # generated from line 407, col 5
                continue
            for componentName in vector.components: # generated from line 410, col 5
                write(u'''#undef ''')
                _v = VFFSL(SL,"componentName",True) # u'$componentName' on line 411, col 8
                if _v is not None: write(_filter(_v, rawExpr=u'$componentName')) # from line 411, col 8.
                write(u'''
''')
        #  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 416, col 3
            if VFN(VFFSL(SL,"field",True),"hasDimension",False)(VFFSL(SL,"dimension",True)): # generated from line 417, col 5
                continue
            # 
            if len([v for v in vectors if v.field.hasDimension(dimension)]) == 0: # generated from line 421, col 5
                continue
            # 
            dimRep = dimension.inBasis(basis)
            if indexOverrides.has_key(dimRep.name): # generated from line 426, col 5
                continue
            write(u'''#undef d''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 429, col 9
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 429, col 9.
            write(u'''
''')
        # 
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict) # u"${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict)}" on line 432, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeaturesInReverseOrder('loopOverFieldInBasisWithVectorsAndInnerContentEnd', featureOrdering, featuresDict)}")) # from line 432, 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 437, 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 VFN(VFFSL(SL,"indexOverrides",True)[VFFSL(SL,"dimRep.name",True)],"has_key",False)(field)
        # 
        write(u'''unsigned long ''')
        _v = VFFSL(SL,"dimRep.loopIndex",True) # u'${dimRep.loopIndex}' on line 444, col 15
        if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.loopIndex}')) # from line 444, col 15.
        write(u''' = ''')
        _v = VFFSL(SL,"indexOverrides",True)[dimRep.name][field] # u'${indexOverrides[dimRep.name][field]}' on line 444, col 37
        if _v is not None: write(_filter(_v, rawExpr=u'${indexOverrides[dimRep.name][field]}')) # from line 444, col 37.
        write(u''';
''')
        #  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 447, col 3
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 448, col 2
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 448, col 2.
            write(u'''_index_pointer += ( 0''')
            write(u''' ''')
            _v = VFFSL(SL,"explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis",False)(vector, dimRep, field, basis, indexOverrides) # u'${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}' on line 449, col 2
            if _v is not None: write(_filter(_v, rawExpr=u'${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}')) # from line 449, col 2.
            write(u''' ) * _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 450, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 450, col 7.
            write(u'''_ncomponents;
''')
        write(u'''
''')
        # 
        
        ########################################
        ## 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 457, 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 462, col 3
            return
        # 
        #  For the vectors that are not in the field $field, set their index pointers
        write(u'''// Set index pointers explicitly for (some) vectors
''')
        for vector in vectorsNeedingExplicitIndexPointers: # generated from line 468, col 3
            # 
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 470, col 2
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 470, col 2.
            write(u'''_index_pointer = ( 0''')
            for dimRep in vector.field.inBasis(basis): # generated from line 471, col 5
                _v = VFFSL(SL,"explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis",False)(vector, dimRep, field, basis, indexOverrides) # u'${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}' on line 472, col 1
                if _v is not None: write(_filter(_v, rawExpr=u'${explicitIndexPointerTermForVectorAndDimRepWithFieldAndBasis(vector, dimRep, field, basis, indexOverrides)}')) # from line 472, col 1.
            write(u''' ) * _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 474, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 474, col 7.
            write(u'''_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 479, 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(u'''
''')
        #  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 490, 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 499, col 5
                write(u'''   + ''')
                _v = VFFSL(SL,"fieldDimRep.loopIndex",True) # u'${fieldDimRep.loopIndex}' on line 500, col 6
                if _v is not None: write(_filter(_v, rawExpr=u'${fieldDimRep.loopIndex}')) # from line 500, col 6.
                write(u''' * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 501, col 4
                if _v is not None: write(_filter(_v, rawExpr=u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 501, col 4.
            else: # generated from line 502, col 5
                write(u'''   + ( ''')
                _v = VFN(VFFSL(SL,"dimRep",True),"localIndexFromIndexForDimensionRep",False)(fieldDimRep) # u'${dimRep.localIndexFromIndexForDimensionRep(fieldDimRep)}' on line 503, col 8
                if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.localIndexFromIndexForDimensionRep(fieldDimRep)}')) # from line 503, col 8.
                write(u''' )''')
                write(u''' * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 504, col 4
                if _v is not None: write(_filter(_v, rawExpr=u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 504, col 4.
        else: # generated from line 506, 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 indexOverrides.has_key(dimRep.name): # generated from line 509, col 5
                #  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)
                write(u'''   + ''')
                _v = VFFSL(SL,"indexOverrides",True)[dimRep.name][vector.field] # u'${indexOverrides[dimRep.name][vector.field]}' on line 514, col 6
                if _v is not None: write(_filter(_v, rawExpr=u'${indexOverrides[dimRep.name][vector.field]}')) # from line 514, col 6.
                write(u'''  * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 515, col 5
                if _v is not None: write(_filter(_v, rawExpr=u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 515, col 5.
            else: # generated from line 516, 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(u'''   + ( ''')
                _v = VFFSL(SL,"dimRep.indexForSinglePointSample",True) # u'${dimRep.indexForSinglePointSample}' on line 525, col 8
                if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.indexForSinglePointSample}')) # from line 525, col 8.
                write(u''' )''')
                write(u'''  * ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(dimRep, basis) # u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)' on line 526, col 5
                if _v is not None: write(_filter(_v, rawExpr=u'$vector.field.localPointsInDimensionsAfterDimRepInBasis(dimRep, basis)')) # from line 526, 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 533, 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 537, col 3
            write(u'''
''')
            #  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 544, col 5
                write(u'''_active_''')
                _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 545, col 9
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 545, col 9.
                write(u'''[_''')
                _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 545, col 23
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 545, col 23.
                write(u'''_index_pointer + ''')
                _v = VFFSL(SL,"componentNumber",True) # u'${componentNumber}' on line 545, col 52
                if _v is not None: write(_filter(_v, rawExpr=u'${componentNumber}')) # from line 545, col 52.
                write(u'''] += ''')
                _v = VFFSL(SL,"componentName",True) # u'${componentName}' on line 545, col 75
                if _v is not None: write(_filter(_v, rawExpr=u'${componentName}')) # from line 545, col 75.
                #  Loop over the dimensions
                for dimension in VFFSL(SL,"dimensionsIntegratedOver",True): # generated from line 547, col 7
                    write(u''' * d''')
                    _v = VFN(VFN(VFFSL(SL,"dimension",True),"inBasis",False)(basis),"name",True) # u'${dimension.inBasis(basis).name}' on line 548, col 5
                    if _v is not None: write(_filter(_v, rawExpr=u'${dimension.inBasis(basis).name}')) # from line 548, col 5.
                write(u''';
''')
        # 
        
        ########################################
        ## 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 557, 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 563, col 3
            return
        write(u'''// Increment index pointers for vectors in field ''')
        _v = VFFSL(SL,"field.name",True) # u'$field.name' on line 566, col 50
        if _v is not None: write(_filter(_v, rawExpr=u'$field.name')) # from line 566, col 50.
        write(u''' (or having the same dimensions)
''')
        for vector in vectors: # generated from line 567, 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(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 577, col 2
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 577, col 2.
            write(u'''_index_pointer += ''')
            _v = VFN(VFFSL(SL,"field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(lastLoopDimRep, basis) # u'$field.localPointsInDimensionsAfterDimRepInBasis(lastLoopDimRep, basis)' on line 577, col 32
            if _v is not None: write(_filter(_v, rawExpr=u'$field.localPointsInDimensionsAfterDimRepInBasis(lastLoopDimRep, basis)')) # from line 577, col 32.
            write(u''' * _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 577, col 107
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 577, col 107.
            write(u'''_ncomponents;
''')
        write(u'''
''')
        # 
        
        ########################################
        ## 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 583, 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 589, col 3
            _v = VFN(VFN(VFFSL(SL,"vector",True),"functions",True)['evaluate'],"call",False)() # u"${vector.functions['evaluate'].call()}" on line 590, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"${vector.functions['evaluate'].call()}")) # from line 590, col 1.
            write(u'''
''')
        # 
        
        ########################################
        ## 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 595, 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 598, col 3
            write(u'''memcpy(''')
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 599, col 8
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 599, col 8.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 599, col 22
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 599, col 22.
            write(u''', ''')
            _v = VFFSL(SL,"srcPrefix",True) # u'${srcPrefix}' on line 599, col 36
            if _v is not None: write(_filter(_v, rawExpr=u'${srcPrefix}')) # from line 599, col 36.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 599, col 49
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 599, col 49.
            write(u''', sizeof(''')
            _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 599, col 70
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 599, col 70.
            write(u''') * ''')
            _v = VFFSL(SL,"vector.allocSize",True) # u'${vector.allocSize}' on line 599, col 88
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.allocSize}')) # from line 599, col 88.
            write(u''');
''')
        # 
        
        ########################################
        ## 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 604, 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(u'''{
''')
        for vector in VFFSL(SL,"vectors",True): # generated from line 608, col 3
            write(u'''  ''')
            _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 609, col 3
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 609, col 3.
            write(u'''* _temp_''')
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 609, col 25
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 609, col 25.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 609, col 39
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 609, col 39.
            write(u''' = ''')
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 609, col 54
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 609, col 54.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 609, col 68
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 609, col 68.
            write(u''';
  ''')
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 610, col 3
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 610, col 3.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 610, col 17
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 610, col 17.
            write(u''' = ''')
            _v = VFFSL(SL,"srcPrefix",True) # u'${srcPrefix}' on line 610, col 32
            if _v is not None: write(_filter(_v, rawExpr=u'${srcPrefix}')) # from line 610, col 32.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 610, col 45
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 610, col 45.
            write(u''';
  ''')
            _v = VFFSL(SL,"srcPrefix",True) # u'${srcPrefix}' on line 611, col 3
            if _v is not None: write(_filter(_v, rawExpr=u'${srcPrefix}')) # from line 611, col 3.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 611, col 16
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 611, col 16.
            write(u''' = _temp_''')
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 611, col 37
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 611, col 37.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 611, col 51
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 611, col 51.
            write(u''';
''')
        write(u'''}
''')
        # 
        
        ########################################
        ## 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 617, 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 620, col 3
            _v = VFFSL(SL,"destPrefix",True) # u'${destPrefix}' on line 621, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${destPrefix}')) # from line 621, col 1.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 621, col 15
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 621, col 15.
            write(u''' = ''')
            _v = VFFSL(SL,"srcPrefix",True) # u'${srcPrefix}' on line 621, col 30
            if _v is not None: write(_filter(_v, rawExpr=u'${srcPrefix}')) # from line 621, col 30.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 621, col 43
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 621, col 43.
            write(u''';
''')
        # 
        
        ########################################
        ## 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
        
        # 
        # 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(u'''



















''')
        
        ########################################
        ## 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://www.CheetahTemplate.org/

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


