#!/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.Segments.Integrators.Integrator import Integrator

##################################################
## 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.30826
__CHEETAH_genTimestamp__ = 'Sat Jan 21 16:04:32 2017'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.2.3/xpdeint/Segments/Integrators/AdaptiveStep.tmpl'
__CHEETAH_srcLastModified__ = 'Fri Oct 11 15:53:08 2013'
__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 AdaptiveStep(Integrator):

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


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

        super(AdaptiveStep, 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 description(self, **KWS):



        ## Generated from @def description: segment $segmentNumber ($stepper.name adaptive-step integrator) at line 24, 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
        
        write(u'''segment ''')
        _v = VFFSL(SL,"segmentNumber",True) # u'$segmentNumber' on line 24, col 27
        if _v is not None: write(_filter(_v, rawExpr=u'$segmentNumber')) # from line 24, col 27.
        write(u''' (''')
        _v = VFFSL(SL,"stepper.name",True) # u'$stepper.name' on line 24, col 43
        if _v is not None: write(_filter(_v, rawExpr=u'$stepper.name')) # from line 24, col 43.
        write(u''' adaptive-step integrator)''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionPrototypes(self, **KWS):



        ## CHEETAH: generated from @def functionPrototypes at line 31, 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
        
        # 
        _v = super(AdaptiveStep, self).functionPrototypes()
        if _v is not None: write(_filter(_v))
        # 
        write(u'''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 35, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 35, col 14.
        write(u'''_setup_sampling(bool* _next_sample_flag, long* _next_sample_counter);
''')
        # 
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 37, col 3
            write(u'''real _segment''')
            _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 38, col 14
            if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 38, col 14.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 38, col 31
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 38, col 31.
            write(u'''_timestep_error(''')
            _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 38, col 59
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 38, col 59.
            write(u'''* _checkfield);
bool _segment''')
            _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 39, col 14
            if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 39, col 14.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 39, col 31
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 39, col 31.
            write(u'''_reset(''')
            _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 39, col 50
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 39, col 50.
            write(u'''* _reset_to);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionImplementations(self, **KWS):



        ## CHEETAH: generated from @def functionImplementations at line 48, 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
        
        # 
        _v = super(AdaptiveStep, self).functionImplementations()
        if _v is not None: write(_filter(_v))
        # 
        _v = VFFSL(SL,"setupSamplingFunctionImplementation",True) # u'${setupSamplingFunctionImplementation}' on line 52, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${setupSamplingFunctionImplementation}')) # from line 52, col 1.
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 53, col 3
            write(u'''
''')
            _v = VFFSL(SL,"timestepErrorFunctionImplementation",False)(VFFSL(SL,"vector",True)) # u'${timestepErrorFunctionImplementation($vector)}' on line 55, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${timestepErrorFunctionImplementation($vector)}')) # from line 55, col 1.
            write(u'''
''')
            _v = VFFSL(SL,"resetFunctionImplementation",False)(VFFSL(SL,"vector",True)) # u'${resetFunctionImplementation($vector)}' on line 57, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${resetFunctionImplementation($vector)}')) # from line 57, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def setupSamplingFunctionImplementation(self, **KWS):



        ## CHEETAH: generated from @def setupSamplingFunctionImplementation at line 63, 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
        
        # 
        write(u'''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 65, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 65, col 14.
        write(u'''_setup_sampling(bool* _next_sample_flag, long* _next_sample_counter)
{
  // The numbers of the moment groups that need to be sampled at the next sampling point.
  // An entry of N+1 means "reached end of integration interval"
  long _momentGroupNumbersNeedingSamplingNext[''')
        _v = VFFSL(SL,"len",False)(VFFSL(SL,"samples",True)) + 1 # u'${len($samples) + 1}' on line 69, col 47
        if _v is not None: write(_filter(_v, rawExpr=u'${len($samples) + 1}')) # from line 69, col 47.
        write(u'''];
  long _numberOfMomentGroupsToBeSampledNext = 1;
  
  long _previous_m = 1;
  long _previous_M = 1;
  
  real _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 75, col 9
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 75, col 9.
        write(u'''_break_next = (real)''')
        _v = VFFSL(SL,"interval",True) # u'${interval}' on line 75, col 52
        if _v is not None: write(_filter(_v, rawExpr=u'${interval}')) # from line 75, col 52.
        write(u''';
  _momentGroupNumbersNeedingSamplingNext[0] = ''')
        _v = VFFSL(SL,"len",False)(VFFSL(SL,"samples",True)) # u'${len($samples)}' on line 76, col 47
        if _v is not None: write(_filter(_v, rawExpr=u'${len($samples)}')) # from line 76, col 47.
        write(u''';
  
  // initialise all flags to false
  for (long _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"len",False)(VFFSL(SL,"samples",True)) + 1 # u'${len($samples) + 1}' on line 79, col 28
        if _v is not None: write(_filter(_v, rawExpr=u'${len($samples) + 1}')) # from line 79, col 28.
        write(u'''; _i0++)
    _next_sample_flag[_i0] = false;
  
  /* Check if moment group needs sampling at the same time as another already discovered sample (or the final time).
   * If so, add this moment group to the to-be-sampled list. If moment group demands sampling earlier than all
   * previously noted moment groups, erase all previous ones from list and set the sample time to this earlier one.
   */
''')
        for momentGroupNumber, sampleCount in enumerate(VFFSL(SL,"samples",True)): # generated from line 86, col 3
            if VFFSL(SL,"sampleCount",True) == 0: # generated from line 87, col 5
                continue
            write(u'''  if (_next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 90, col 28
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 90, col 28.
            write(u'''] * _previous_M == _previous_m * ''')
            _v = VFFSL(SL,"sampleCount",True) # u'$sampleCount' on line 90, col 79
            if _v is not None: write(_filter(_v, rawExpr=u'$sampleCount')) # from line 90, col 79.
            write(u''') {
    _momentGroupNumbersNeedingSamplingNext[_numberOfMomentGroupsToBeSampledNext] = ''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 91, col 84
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 91, col 84.
            write(u''';
    _numberOfMomentGroupsToBeSampledNext++;
  } else if (_next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 93, col 35
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 93, col 35.
            write(u'''] * _previous_M < _previous_m * ''')
            _v = VFFSL(SL,"sampleCount",True) # u'$sampleCount' on line 93, col 85
            if _v is not None: write(_filter(_v, rawExpr=u'$sampleCount')) # from line 93, col 85.
            write(u''') {
    _''')
            _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 94, col 6
            if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 94, col 6.
            write(u'''_break_next = _next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 94, col 64
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 94, col 64.
            write(u'''] * ((real)''')
            _v = VFFSL(SL,"interval",True) # u'$interval' on line 94, col 93
            if _v is not None: write(_filter(_v, rawExpr=u'$interval')) # from line 94, col 93.
            write(u''') / ((real)''')
            _v = VFFSL(SL,"sampleCount",True) # u'$sampleCount' on line 94, col 113
            if _v is not None: write(_filter(_v, rawExpr=u'$sampleCount')) # from line 94, col 113.
            write(u''');
    _numberOfMomentGroupsToBeSampledNext = 1;
    _momentGroupNumbersNeedingSamplingNext[0] = ''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 96, col 49
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 96, col 49.
            write(u''';
    _previous_M = ''')
            _v = VFFSL(SL,"sampleCount",True) # u'$sampleCount' on line 97, col 19
            if _v is not None: write(_filter(_v, rawExpr=u'$sampleCount')) # from line 97, col 19.
            write(u''';
    _previous_m = _next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # u'$momentGroupNumber' on line 98, col 40
            if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupNumber')) # from line 98, col 40.
            write(u'''];
  }
  
''')
        write(u'''  // _momentGroupNumbersNeedingSamplingNext now contains the complete list of moment groups that need
  // to be sampled at the next sampling point. Set their flags to true.
  for (long _i0 = 0; _i0 < _numberOfMomentGroupsToBeSampledNext; _i0++)
    _next_sample_flag[_momentGroupNumbersNeedingSamplingNext[_i0]] = true;
  
  return _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 107, col 11
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 107, col 11.
        write(u'''_break_next;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def timestepErrorFunctionImplementation(self, vector, **KWS):



        ## CHEETAH: generated from @def timestepErrorFunctionImplementation($vector) at line 113, 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
        
        # 
        write(u'''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 115, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 115, col 14.
        write(u'''_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 115, col 31
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 115, col 31.
        write(u'''_timestep_error(''')
        _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 115, col 59
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 115, col 59.
        write(u'''* _checkfield)
{
  real _error = 1e-24;
  real _temp_error = 0.0;
  real _temp_mod = 0.0;

''')
        featureOrdering = ['Diagnostics']
        dict = {'vector': vector}
        write(u'''  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('timestepErrorBegin', featureOrdering, {'vector': vector}) # u"${insertCodeForFeatures('timestepErrorBegin', featureOrdering, {'vector': vector}), autoIndent=True}" on line 123, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('timestepErrorBegin', featureOrdering, {'vector': vector}), autoIndent=True}")) # from line 123, col 3.
        write(u'''  
''')
        if len(VFFSL(SL,"vector.field.dimensions",True)) > 0: # generated from line 125, col 3
            #  FIXME: We need to have the capacity to have both a peak cutoff and an absolute cutoff
            write(u'''  // Find the peak value for each component of the field
  real _cutoff[_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 128, col 17
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 128, col 17.
            write(u'''_ncomponents];
  
  for (long _i0 = 0; _i0 < _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 130, col 29
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 130, col 29.
            write(u'''_ncomponents; _i0++)
    _cutoff[_i0] = 0.0;
  
  {
    ''')
            _v = VFFSL(SL,"loopOverVectorsInBasisWithInnerContent",False)([vector], VFFSL(SL,"homeBasis",True), VFFSL(SL,"insideFindPeakLoops",False)(vector)) # u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindPeakLoops(vector)), autoIndent=True}' on line 134, col 5
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindPeakLoops(vector)), autoIndent=True}')) # from line 134, col 5.
            write(u'''  }
  ''')
            _v = VFFSL(SL,"insertCodeForFeatures",False)('findMax', ['Driver'], {'variable': '_cutoff', 'count': ''.join([u'_',str(VFFSL(SL,"vector.id",True)),u'_ncomponents'])}) # u"${insertCodeForFeatures('findMax', ['Driver'], {'variable': '_cutoff', 'count': c'_${vector.id}_ncomponents'}), autoIndent=True}" on line 136, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('findMax', ['Driver'], {'variable': '_cutoff', 'count': c'_${vector.id}_ncomponents'}), autoIndent=True}")) # from line 136, col 3.
            write(u'''  
  for (long _i0 = 0; _i0 < _''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 138, col 29
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 138, col 29.
            write(u'''_ncomponents; _i0++) {
    if (_xmds_isnonfinite(_cutoff[_i0]))
      // Return an error two times the tolerance in this case because the timestep must be reduced.
      return 2.0*''')
            _v = VFFSL(SL,"tolerance",True) # u'${tolerance}' on line 141, col 18
            if _v is not None: write(_filter(_v, rawExpr=u'${tolerance}')) # from line 141, col 18.
            write(u''';
    _cutoff[_i0] *= ''')
            _v = VFFSL(SL,"cutoff",True) # u'${cutoff}' on line 142, col 21
            if _v is not None: write(_filter(_v, rawExpr=u'${cutoff}')) # from line 142, col 21.
            write(u''';
''')
            if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 143, col 5
                #  multiply again because we are using norm for our complex vector and the cutoff should be interpreted in terms of
                #  the absolute magnitude of the variables, not the mod-square
                write(u'''    _cutoff[_i0] *= ''')
                _v = VFFSL(SL,"cutoff",True) # u'${cutoff}' on line 146, col 21
                if _v is not None: write(_filter(_v, rawExpr=u'${cutoff}')) # from line 146, col 21.
                write(u''';
''')
            write(u'''  }
''')
        write(u'''  
''')
        #  Code for absolute cutoff should go here and modify
        #  the _cutoff variables
        # 
        #  @for $absoluteCutoff in $absoluteCutoffs
        #  // absolute cutoff for component '$absoluteCutoff.name'
        #  if (_cutoff[${absoluteCutoff.componentIndex}])
        #  @end for
        # 
        write(u'''  {
    ''')
        _v = VFFSL(SL,"loopOverVectorsInBasisWithInnerContent",False)([vector], VFFSL(SL,"homeBasis",True), VFFSL(SL,"insideFindMaxErrorLoops",False)(vector)) # u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindMaxErrorLoops(vector)), autoIndent=True}' on line 160, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindMaxErrorLoops(vector)), autoIndent=True}')) # from line 160, col 5.
        write(u'''  }
  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}) # u"${insertCodeForFeatures('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}), autoIndent=True}" on line 162, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}), autoIndent=True}")) # from line 162, col 3.
        write(u'''  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('timestepErrorEnd', featureOrdering, dict) # u"${insertCodeForFeaturesInReverseOrder('timestepErrorEnd', featureOrdering, dict), autoIndent=True}" on line 163, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeaturesInReverseOrder('timestepErrorEnd', featureOrdering, dict), autoIndent=True}")) # from line 163, col 3.
        write(u'''  
  return _error;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def insideFindPeakLoops(self, vector, **KWS):



        ## CHEETAH: generated from @def insideFindPeakLoops($vector) 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
        
        # 
        write(u'''for (long _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 173, col 27
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 173, col 27.
        write(u'''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 174, col 3
            modFunction = 'mod2'
        else: # generated from line 176, col 3
            modFunction = 'abs'
        write(u'''  _temp_mod = ''')
        _v = VFFSL(SL,"modFunction",True) # u'${modFunction}' on line 179, col 15
        if _v is not None: write(_filter(_v, rawExpr=u'${modFunction}')) # from line 179, col 15.
        write(u'''(_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 179, col 31
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 179, col 31.
        write(u'''[_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 179, col 45
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 179, col 45.
        write(u'''_index_pointer + _i1]);
  if (_xmds_isnonfinite(_temp_mod))
    _cutoff[_i1] = INFINITY;
  else if (_cutoff[_i1] < _temp_mod)
    _cutoff[_i1] = _temp_mod;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def insideFindMaxErrorLoops(self, vector, **KWS):



        ## CHEETAH: generated from @def insideFindMaxErrorLoops($vector) at line 189, 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
        
        # 
        write(u'''for (long  _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 191, col 28
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 191, col 28.
        write(u'''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 192, col 3
            modCutoffFunction = 'mod2'
        else: # generated from line 194, col 3
            modCutoffFunction = 'abs'
        if len(VFFSL(SL,"vector.field.dimensions",True)) > 0: # generated from line 197, col 3
            write(u'''  if (''')
            _v = VFFSL(SL,"modCutoffFunction",True) # u'${modCutoffFunction}' on line 198, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${modCutoffFunction}')) # from line 198, col 7.
            write(u'''(_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 198, col 29
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 198, col 29.
            write(u'''[_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 198, col 43
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 198, col 43.
            write(u'''_index_pointer + _i1]) > _cutoff[_i1]) {
    ''')
            _v = VFFSL(SL,"updateMaximumError",False)(VFFSL(SL,"vector",True)) # u'${updateMaximumError($vector), autoIndent=True}' on line 199, col 5
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${updateMaximumError($vector), autoIndent=True}')) # from line 199, col 5.
            write(u'''  }
''')
        else: # generated from line 201, col 3
            write(u'''  ''')
            _v = VFFSL(SL,"updateMaximumError",False)(VFFSL(SL,"vector",True)) # u'${updateMaximumError($vector), autoIndent=True}' on line 202, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${updateMaximumError($vector), autoIndent=True}')) # from line 202, col 3.
        write(u'''}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def insideLookForNaNLoops(self, vector, **KWS):



        ## CHEETAH: generated from @def insideLookForNaNLoops($vector) at line 208, 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
        
        # 
        #  No point in fancy logic trying to exit the test early if a NaN is found, even
        #  though this is hot path code, since a NaN means we're about to exit the simulation
        #  anyway. Worth having seperate code depending on whether the vector values are
        #  real or complex though, since complex requires either two checks or taking the
        #  modulus. Presumably two seperate Re(), Im() checks are faster than mod2
        # 
        write(u'''  for (long _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 216, col 29
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 216, col 29.
        write(u'''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 217, col 3
            write(u'''    if (_xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 218, col 28
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 218, col 28.
            write(u'''[_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 218, col 42
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 218, col 42.
            write(u'''_index_pointer + _i1].Re())
      || _xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 219, col 29
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 219, col 29.
            write(u'''[_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 219, col 43
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 219, col 43.
            write(u'''_index_pointer + _i1].Im())) bNoNaNsPresent = false;
''')
        else: # generated from line 220, col 3
            write(u'''    if (_xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 221, col 28
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 221, col 28.
            write(u'''[_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 221, col 42
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 221, col 42.
            write(u'''_index_pointer + _i1])) bNoNaNsPresent = false;
''')
        write(u'''  }
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def updateMaximumError(self, vector, **KWS):



        ## CHEETAH: generated from @def updateMaximumError($vector) at line 227, 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
        
        # 
        write(u'''_temp_error = abs(_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 20
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 20.
        write(u'''[_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 34
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 34.
        write(u'''_index_pointer + _i1] - _checkfield[_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 83
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 83.
        write(u'''_index_pointer + _i1]) / (0.5*abs(_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 130
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 130.
        write(u'''[_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 144
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 144.
        write(u'''_index_pointer + _i1]) + 0.5*abs(_checkfield[_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 229, col 202
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 229, col 202.
        write(u'''_index_pointer + _i1]));

if (_xmds_isnonfinite(_temp_error)) {
  /* For _temp_error to be NaN, both the absolute value of the higher and lower order solutions
     must BOTH be zero. This therefore implies that their difference is zero, and that there is no error. */
  _temp_error = 0.0;
}

if (_error < _temp_error) // UNVECTORISABLE
  _error = _temp_error;
''')
        # 
        _v = VFFSL(SL,"insertCodeForFeatures",False)('updateMaximumError', ['Diagnostics'], {'vector': vector}) # u"${insertCodeForFeatures('updateMaximumError', ['Diagnostics'], {'vector': vector})}" on line 240, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('updateMaximumError', ['Diagnostics'], {'vector': vector})}")) # from line 240, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def resetFunctionImplementation(self, vector, **KWS):



        ## CHEETAH: generated from @def resetFunctionImplementation($vector) at line 245, 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
        
        # 
        write(u'''bool _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 247, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 247, col 14.
        write(u'''_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 247, col 31
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 247, col 31.
        write(u'''_reset(''')
        _v = VFFSL(SL,"vector.type",True) # u'${vector.type}' on line 247, col 50
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.type}')) # from line 247, col 50.
        write(u'''* _reset_to_''')
        _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 247, col 76
        if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 247, col 76.
        write(u''')
{
  ''')
        _v = VFFSL(SL,"copyVectors",False)([vector], destPrefix = '', srcPrefix = '_reset_to') # u"${copyVectors([vector], destPrefix = '', srcPrefix = '_reset_to'), autoIndent=True}" on line 249, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${copyVectors([vector], destPrefix = '', srcPrefix = '_reset_to'), autoIndent=True}")) # from line 249, col 3.
        write(u"""  
  /* return false if there's a NaN somewhere in the vector, otherwise return true */
  bool bNoNaNsPresent = true;
  {
    """)
        _v = VFFSL(SL,"loopOverVectorsInBasisWithInnerContent",False)([vector], VFFSL(SL,"homeBasis",True), VFFSL(SL,"insideLookForNaNLoops",False)(vector)) # u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideLookForNaNLoops(vector)), autoIndent=True}' on line 254, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideLookForNaNLoops(vector)), autoIndent=True}')) # from line 254, col 5.
        write(u'''  }
  return bNoNaNsPresent;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def createToleranceVariable(self, **KWS):


        """
        This function returns the code that will create a _step variable,
        including any modifications necessary due to the ErrorCheck feature.
        """

        ## CHEETAH: generated from @def createToleranceVariable at line 261, 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
        
        # 
        write(u'''real _tolerance = ''')
        _v = VFFSL(SL,"tolerance",True) # u'${tolerance}' on line 267, col 19
        if _v is not None: write(_filter(_v, rawExpr=u'${tolerance}')) # from line 267, col 19.
        write(u''';
''')
        # 
        featureOrdering = ['ErrorCheck']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('createToleranceVariable', featureOrdering) # u"${insertCodeForFeatures('createToleranceVariable', featureOrdering)}" on line 270, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('createToleranceVariable', featureOrdering)}")) # from line 270, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def segmentFunctionBody(self, function, **KWS):



        ## CHEETAH: generated from @def segmentFunctionBody($function) at line 274, 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
        
        # 
        write(u'''real _step = ''')
        _v = VFFSL(SL,"interval",True) # u'${interval}' on line 276, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${interval}')) # from line 276, col 14.
        write(u'''/(real)''')
        _v = VFFSL(SL,"stepCount",True) # u'${stepCount}' on line 276, col 32
        if _v is not None: write(_filter(_v, rawExpr=u'${stepCount}')) # from line 276, col 32.
        write(u''';
real _old_step = _step;
real _min_step = _step;
real _max_step = _step;
long _attempted_steps = 0;
long _unsuccessful_steps = 0;

''')
        _v = VFFSL(SL,"createToleranceVariable",True) # u'${createToleranceVariable}' on line 283, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${createToleranceVariable}')) # from line 283, col 1.
        #  Insert code for features
        featureOrderingOuter = ['Stochastic']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepBegin', featureOrderingOuter) # u"${insertCodeForFeatures('integrateAdaptiveStepBegin', featureOrderingOuter)}" on line 286, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('integrateAdaptiveStepBegin', featureOrderingOuter)}")) # from line 286, col 1.
        write(u'''
real _error, _last_norm_error = 1.0;
''')
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 289, col 3
            write(u'''real _''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 290, col 7
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 290, col 7.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 290, col 15
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 290, col 15.
            write(u'''_error;
''')
        write(u'''
bool _discard = false;
bool _break_next = false;

''')
        momentGroupCount = len(VFFSL(SL,"momentGroups",True))
        write(u'''bool _next_sample_flag[''')
        _v = VFFSL(SL,"momentGroupCount",True) + 2 # u'${momentGroupCount + 2}' on line 297, col 24
        if _v is not None: write(_filter(_v, rawExpr=u'${momentGroupCount + 2}')) # from line 297, col 24.
        write(u'''];
for (long _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"momentGroupCount",True) + 2 # u'${momentGroupCount + 2}' on line 298, col 26
        if _v is not None: write(_filter(_v, rawExpr=u'${momentGroupCount + 2}')) # from line 298, col 26.
        write(u'''; _i0++)
  _next_sample_flag[_i0] = false;

long _next_sample_counter[''')
        _v = VFFSL(SL,"momentGroupCount",True) # u'$momentGroupCount' on line 301, col 27
        if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupCount')) # from line 301, col 27.
        write(u'''];
for (long _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"momentGroupCount",True) # u'$momentGroupCount' on line 302, col 26
        if _v is not None: write(_filter(_v, rawExpr=u'$momentGroupCount')) # from line 302, col 26.
        write(u'''; _i0++)
  _next_sample_counter[_i0] = 1;

real _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 305, col 7
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 305, col 7.
        write(u'''_local = 0.0;

real _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 307, col 7
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 307, col 7.
        write(u'''_break_next = _''')
        _v = VFFSL(SL,"name",True) # u'${name}' on line 307, col 45
        if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 307, col 45.
        write(u'''_setup_sampling(_next_sample_flag, _next_sample_counter);

if ( (_''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 309, col 8
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 309, col 8.
        write(u'''_local + _step)*(1.0 + _EPSILON) >= _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 309, col 68
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 309, col 68.
        write(u'''_break_next) {
  _break_next = true;
  _step = _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 311, col 12
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 311, col 12.
        write(u'''_break_next - _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 311, col 50
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 311, col 50.
        write(u'''_local;
}

''')
        _v = VFFSL(SL,"allocate",True) # u'${allocate}' on line 314, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${allocate}')) # from line 314, col 1.
        _v = VFFSL(SL,"initialise",True) # u'${initialise}' on line 315, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${initialise}')) # from line 315, col 1.
        _v = VFFSL(SL,"localInitialise",True) # u'${localInitialise}' on line 316, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${localInitialise}')) # from line 316, col 1.
        write(u'''
do {
''')
        featureOrderingOuterLoop = ['MaxIterations', 'Output', 'ErrorCheck']
        write(u'''  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop) # u"${insertCodeForFeatures('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop), autoIndent=True}" on line 320, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop), autoIndent=True}")) # from line 320, col 3.
        write(u'''  
  ''')
        _v = VFFSL(SL,"preSingleStep",True) # u'${preSingleStep, autoIndent=True}' on line 322, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${preSingleStep, autoIndent=True}')) # from line 322, col 3.
        write(u'''  do {
''')
        #  Insert code for features
        featureOrderingInnerLoop = ['Stochastic']
        write(u'''    ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop) # u"${insertCodeForFeatures('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop), autoIndent=True}" on line 326, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop), autoIndent=True}")) # from line 326, col 5.
        write(u'''    
    ''')
        _v = VFN(VFFSL(SL,"stepper",True),"singleIntegrationStep",False)(function) # u'${stepper.singleIntegrationStep(function), autoIndent=True}' on line 328, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${stepper.singleIntegrationStep(function), autoIndent=True}')) # from line 328, col 5.
        write(u'''    
    ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop) # u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop), autoIndent=True}" on line 330, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop), autoIndent=True}")) # from line 330, col 5.
        write(u'''    
    _error = 0.0;
''')
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 333, col 3
            write(u'''    
    _''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 335, col 6
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 335, col 6.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 335, col 14
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 335, col 14.
            write(u'''_error = _''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 335, col 36
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 335, col 36.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 335, col 44
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 335, col 44.
            write(u'''_timestep_error(_''')
            _v = VFFSL(SL,"stepper.errorFieldName",True) # u'${stepper.errorFieldName}' on line 335, col 73
            if _v is not None: write(_filter(_v, rawExpr=u'${stepper.errorFieldName}')) # from line 335, col 73.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 335, col 99
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 335, col 99.
            write(u''');
    if (_''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 336, col 10
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 336, col 10.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 336, col 18
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 336, col 18.
            write(u'''_error > _error)
      _error = _''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 337, col 17
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 337, col 17.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 337, col 25
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 337, col 25.
            write(u'''_error;
''')
        write(u'''    
    _attempted_steps++;
    
''')
        featureOrderingForToleranceChecking = ['Diagnostics', 'Stochastic']
        write(u'''    if (_error < _tolerance) {
      ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('adaptiveStepSucceeded', VFFSL(SL,"featureOrderingForToleranceChecking",True)) # u"${insertCodeForFeatures('adaptiveStepSucceeded', $featureOrderingForToleranceChecking), autoIndent=True}" on line 344, col 7
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('adaptiveStepSucceeded', $featureOrderingForToleranceChecking), autoIndent=True}")) # from line 344, col 7.
        write(u'''      _''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 345, col 8
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 345, col 8.
        write(u'''_local += _step;
      if (_step > _max_step)
        _max_step = _step;
      if (!_break_next && _step < _min_step)
        _min_step = _step;
      _discard = false;
    } else {
      ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('adaptiveStepFailed', VFFSL(SL,"featureOrderingForToleranceChecking",True)) # u"${insertCodeForFeatures('adaptiveStepFailed', $featureOrderingForToleranceChecking), autoIndent=True}" on line 352, col 7
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('adaptiveStepFailed', $featureOrderingForToleranceChecking), autoIndent=True}")) # from line 352, col 7.
        write(u'''      ''')
        _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 353, col 7
        if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 353, col 7.
        write(u''' -= _step;

''')
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 355, col 3
            write(u'''      if (_''')
            _v = VFFSL(SL,"name",True) # u'${name}' on line 356, col 12
            if _v is not None: write(_filter(_v, rawExpr=u'${name}')) # from line 356, col 12.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 356, col 20
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 356, col 20.
            write(u'''_reset(_''')
            _v = VFFSL(SL,"stepper.resetFieldName",True) # u'${stepper.resetFieldName}' on line 356, col 40
            if _v is not None: write(_filter(_v, rawExpr=u'${stepper.resetFieldName}')) # from line 356, col 40.
            write(u'''_''')
            _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 356, col 66
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 356, col 66.
            write(u''') == false) {

        _LOG(_WARNING_LOG_LEVEL, "WARNING: NaN present. Integration halted at ''')
            _v = VFFSL(SL,"propagationDimension",True) # u'${propagationDimension}' on line 358, col 79
            if _v is not None: write(_filter(_v, rawExpr=u'${propagationDimension}')) # from line 358, col 79.
            write(u''' = %e.\\n"
                           "         Non-finite number in integration vector \\"''')
            _v = VFFSL(SL,"vector.name",True) # u'${vector.name}' on line 359, col 80
            if _v is not None: write(_filter(_v, rawExpr=u'${vector.name}')) # from line 359, col 80.
            write(u'''\\" in segment ''')
            _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 359, col 108
            if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 359, col 108.
            write(u'''.\\n", ''')
            _v = VFFSL(SL,"propagationDimension",True) # u'$propagationDimension' on line 359, col 130
            if _v is not None: write(_filter(_v, rawExpr=u'$propagationDimension')) # from line 359, col 130.
            write(u''');
        ''')
            _v = VFFSL(SL,"earlyTerminationCode",True) # u'${earlyTerminationCode, autoIndent=True}' on line 360, col 9
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${earlyTerminationCode, autoIndent=True}')) # from line 360, col 9.
            write(u'''      }
''')
        write(u'''
      ''')
        _v = VFN(VFFSL(SL,"functions",True)['ipEvolve'],"call",False)(_exponent = -1, parentFunction=function) # u"${functions['ipEvolve'].call(_exponent = -1, parentFunction=function)}" on line 364, col 7
        if _v is not None: write(_filter(_v, rawExpr=u"${functions['ipEvolve'].call(_exponent = -1, parentFunction=function)}")) # from line 364, col 7.
        write(u'''
      
      _discard = true;
      _break_next = false;
      _unsuccessful_steps++;
    }
    
    _old_step = _step;
    
    // Resize step
    if (_error < 0.5*_tolerance || _error > _tolerance) {
      const real _safetyFactor = 0.90;
      real _scalingFactor = _safetyFactor * pow(abs(_error/_tolerance), real(-0.7/''')
        _v = VFFSL(SL,"integrationOrder",True) # u'${integrationOrder}' on line 376, col 83
        if _v is not None: write(_filter(_v, rawExpr=u'${integrationOrder}')) # from line 376, col 83.
        write(u''')) * pow(_last_norm_error, real(0.4/''')
        _v = VFFSL(SL,"integrationOrder",True) # u'${integrationOrder}' on line 376, col 138
        if _v is not None: write(_filter(_v, rawExpr=u'${integrationOrder}')) # from line 376, col 138.
        write(u"""));
      _scalingFactor = MAX(_scalingFactor, 1.0/5.0);
      _scalingFactor = MIN(_scalingFactor, 7.0);
      if (_error > _tolerance && _scalingFactor > 1.0) {
        // If our step failed don't try and increase our step size. That would be silly.
        _scalingFactor = _safetyFactor * pow(abs(_error/_tolerance), real(-1.0/""")
        _v = VFFSL(SL,"integrationOrder",True) # u'${integrationOrder}' on line 381, col 80
        if _v is not None: write(_filter(_v, rawExpr=u'${integrationOrder}')) # from line 381, col 80.
        write(u'''));
      }
      _old_step = _step;
      _last_norm_error = pow(_safetyFactor/_scalingFactor*pow(_last_norm_error, real(0.4/''')
        _v = VFFSL(SL,"integrationOrder",True) # u'${integrationOrder}' on line 384, col 90
        if _v is not None: write(_filter(_v, rawExpr=u'${integrationOrder}')) # from line 384, col 90.
        write(u''')), real(''')
        _v = VFFSL(SL,"integrationOrder",True) # u'${integrationOrder}' on line 384, col 118
        if _v is not None: write(_filter(_v, rawExpr=u'${integrationOrder}')) # from line 384, col 118.
        write(u'''/0.7));
      _step *= _scalingFactor;
    }
    
  } while (_discard);
  ''')
        _v = VFFSL(SL,"postSingleStep",True) # u'${postSingleStep, autoIndent=True}' on line 389, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${postSingleStep, autoIndent=True}')) # from line 389, col 3.
        write(u'''  
  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop) # u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop), autoIndent=True}" on line 391, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop), autoIndent=True}")) # from line 391, col 3.
        write(u'''} while (!_next_sample_flag[''')
        _v = VFFSL(SL,"momentGroupCount",True) + 1 # u'${momentGroupCount + 1}' on line 392, col 29
        if _v is not None: write(_filter(_v, rawExpr=u'${momentGroupCount + 1}')) # from line 392, col 29.
        write(u''']);

''')
        _v = VFFSL(SL,"localFinalise",True) # u'${localFinalise}' on line 394, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${localFinalise}')) # from line 394, col 1.
        _v = VFFSL(SL,"finalise",True) # u'${finalise}' on line 395, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${finalise}')) # from line 395, col 1.
        _v = VFFSL(SL,"free",True) # u'${free}' on line 396, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${free}')) # from line 396, col 1.
        # 
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepEnd', featureOrderingOuter) # u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepEnd', featureOrderingOuter)}" on line 398, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepEnd', featureOrderingOuter)}")) # from line 398, col 1.
        write(u'''
_LOG(_SEGMENT_LOG_LEVEL, "Segment ''')
        _v = VFFSL(SL,"segmentNumber",True) # u'${segmentNumber}' on line 400, col 35
        if _v is not None: write(_filter(_v, rawExpr=u'${segmentNumber}')) # from line 400, col 35.
        write(u''': minimum timestep: %e maximum timestep: %e\\n", _min_step, _max_step);
_LOG(_SEGMENT_LOG_LEVEL, "  Attempted %li steps, %.2f%% steps failed.\\n", _attempted_steps, (100.0*_unsuccessful_steps)/_attempted_steps);
''')
        # 
        
        ########################################
        ## 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(u'''F''')
        # 
        # AdaptiveStep.tmpl
        # 
        # Created by Graham Dennis on 2007-11-16.
        # 
        # 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'''



''')
        # 
        #   Function prototypes
        write(u'''

''')
        # 
        #   Function implementations
        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__

    supportsConstantIPOperators = False

    _mainCheetahMethod_for_AdaptiveStep= 'writeBody'

## END CLASS DEFINITION

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


# 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=AdaptiveStep()).run()


