#!/usr/bin/env python3




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

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.3'
__CHEETAH_versionTuple__ = (3, 2, 3, 'final', 0)
__CHEETAH_genTime__ = 1558054970.4857848
__CHEETAH_genTimestamp__ = 'Fri May 17 11:02:50 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-3.0.0/xpdeint/Segments/Integrators/AdaptiveStep.tmpl'
__CHEETAH_srcLastModified__ = 'Thu Apr  4 16:29:24 2019'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'

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

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

class 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 26, 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('''segment ''')
        _v = VFFSL(SL,"segmentNumber",True) # '$segmentNumber' on line 26, col 27
        if _v is not None: write(_filter(_v, rawExpr='$segmentNumber')) # from line 26, col 27.
        write(''' (''')
        _v = VFFSL(SL,"stepper.name",True) # '$stepper.name' on line 26, col 43
        if _v is not None: write(_filter(_v, rawExpr='$stepper.name')) # from line 26, col 43.
        write(''' 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 33, 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('''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 37, col 14
        if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 37, col 14.
        write('''_setup_sampling(bool* _next_sample_flag, long* _next_sample_counter);
''')
        # 
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 39, col 3
            write('''real _segment''')
            _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 40, col 14
            if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 40, col 14.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 40, col 31
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 40, col 31.
            write('''_timestep_error(''')
            _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 40, col 59
            if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 40, col 59.
            write('''* _checkfield);
bool _segment''')
            _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 41, col 14
            if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 41, col 14.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 41, col 31
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 41, col 31.
            write('''_reset(''')
            _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 41, col 50
            if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 41, col 50.
            write('''* _reset_to);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionImplementations(self, **KWS):



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

    def setupSamplingFunctionImplementation(self, **KWS):



        ## CHEETAH: generated from @def setupSamplingFunctionImplementation at line 65, 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('''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 67, col 14
        if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 67, col 14.
        write('''_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 # '${len($samples) + 1}' on line 71, col 47
        if _v is not None: write(_filter(_v, rawExpr='${len($samples) + 1}')) # from line 71, col 47.
        write('''];
  long _numberOfMomentGroupsToBeSampledNext = 1;
  
  long _previous_m = 1;
  long _previous_M = 1;
  
  real _''')
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 77, col 9
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 77, col 9.
        write('''_break_next = (real)''')
        _v = VFFSL(SL,"interval",True) # '${interval}' on line 77, col 52
        if _v is not None: write(_filter(_v, rawExpr='${interval}')) # from line 77, col 52.
        write(''';
  _momentGroupNumbersNeedingSamplingNext[0] = ''')
        _v = VFFSL(SL,"len",False)(VFFSL(SL,"samples",True)) # '${len($samples)}' on line 78, col 47
        if _v is not None: write(_filter(_v, rawExpr='${len($samples)}')) # from line 78, col 47.
        write(''';
  
  // initialise all flags to false
  for (long _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"len",False)(VFFSL(SL,"samples",True)) + 1 # '${len($samples) + 1}' on line 81, col 28
        if _v is not None: write(_filter(_v, rawExpr='${len($samples) + 1}')) # from line 81, col 28.
        write('''; _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 88, col 3
            if VFFSL(SL,"sampleCount",True) == 0: # generated from line 89, col 5
                continue
            write('''  if (_next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 92, col 28
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 92, col 28.
            write('''] * _previous_M == _previous_m * ''')
            _v = VFFSL(SL,"sampleCount",True) # '$sampleCount' on line 92, col 79
            if _v is not None: write(_filter(_v, rawExpr='$sampleCount')) # from line 92, col 79.
            write(''') {
    _momentGroupNumbersNeedingSamplingNext[_numberOfMomentGroupsToBeSampledNext] = ''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 93, col 84
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 93, col 84.
            write(''';
    _numberOfMomentGroupsToBeSampledNext++;
  } else if (_next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 95, col 35
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 95, col 35.
            write('''] * _previous_M < _previous_m * ''')
            _v = VFFSL(SL,"sampleCount",True) # '$sampleCount' on line 95, col 85
            if _v is not None: write(_filter(_v, rawExpr='$sampleCount')) # from line 95, col 85.
            write(''') {
    _''')
            _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 96, col 6
            if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 96, col 6.
            write('''_break_next = _next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 96, col 64
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 96, col 64.
            write('''] * ((real)''')
            _v = VFFSL(SL,"interval",True) # '$interval' on line 96, col 93
            if _v is not None: write(_filter(_v, rawExpr='$interval')) # from line 96, col 93.
            write(''') / ((real)''')
            _v = VFFSL(SL,"sampleCount",True) # '$sampleCount' on line 96, col 113
            if _v is not None: write(_filter(_v, rawExpr='$sampleCount')) # from line 96, col 113.
            write(''');
    _numberOfMomentGroupsToBeSampledNext = 1;
    _momentGroupNumbersNeedingSamplingNext[0] = ''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 98, col 49
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 98, col 49.
            write(''';
    _previous_M = ''')
            _v = VFFSL(SL,"sampleCount",True) # '$sampleCount' on line 99, col 19
            if _v is not None: write(_filter(_v, rawExpr='$sampleCount')) # from line 99, col 19.
            write(''';
    _previous_m = _next_sample_counter[''')
            _v = VFFSL(SL,"momentGroupNumber",True) # '$momentGroupNumber' on line 100, col 40
            if _v is not None: write(_filter(_v, rawExpr='$momentGroupNumber')) # from line 100, col 40.
            write('''];
  }
  
''')
        write('''  // _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) # '${propagationDimension}' on line 109, col 11
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 109, col 11.
        write('''_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 115, 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('''real _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 117, col 14
        if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 117, col 14.
        write('''_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 117, col 31
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 117, col 31.
        write('''_timestep_error(''')
        _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 117, col 59
        if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 117, col 59.
        write('''* _checkfield)
{
  real _error = 1e-24;
  real _temp_error = 0.0;
  real _temp_mod = 0.0;

''')
        featureOrdering = ['Diagnostics']
        dict = {'vector': vector}
        write('''  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('timestepErrorBegin', featureOrdering, {'vector': vector}) # "${insertCodeForFeatures('timestepErrorBegin', featureOrdering, {'vector': vector}), autoIndent=True}" on line 125, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('timestepErrorBegin', featureOrdering, {'vector': vector}), autoIndent=True}")) # from line 125, col 3.
        write('''  
''')
        if len(VFFSL(SL,"vector.field.dimensions",True)) > 0: # generated from line 127, col 3
            #  FIXME: We need to have the capacity to have both a peak cutoff and an absolute cutoff
            write('''  // Find the peak value for each component of the field
  real _cutoff[_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 130, col 17
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 130, col 17.
            write('''_ncomponents];
  
  for (long _i0 = 0; _i0 < _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 132, col 29
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 132, col 29.
            write('''_ncomponents; _i0++)
    _cutoff[_i0] = 0.0;
  
  {
    ''')
            _v = VFFSL(SL,"loopOverVectorsInBasisWithInnerContent",False)([vector], VFFSL(SL,"homeBasis",True), VFFSL(SL,"insideFindPeakLoops",False)(vector)) # '${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindPeakLoops(vector)), autoIndent=True}' on line 136, col 5
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindPeakLoops(vector)), autoIndent=True}')) # from line 136, col 5.
            write('''  }
  ''')
            _v = VFFSL(SL,"insertCodeForFeatures",False)('findMax', ['Driver'], {'variable': '_cutoff', 'count': ''.join(['_',str(VFFSL(SL,"vector.id",True)),'_ncomponents'])}) # "${insertCodeForFeatures('findMax', ['Driver'], {'variable': '_cutoff', 'count': c'_${vector.id}_ncomponents'}), autoIndent=True}" on line 138, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('findMax', ['Driver'], {'variable': '_cutoff', 'count': c'_${vector.id}_ncomponents'}), autoIndent=True}")) # from line 138, col 3.
            write('''  
  for (long _i0 = 0; _i0 < _''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 140, col 29
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 140, col 29.
            write('''_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) # '${tolerance}' on line 143, col 18
            if _v is not None: write(_filter(_v, rawExpr='${tolerance}')) # from line 143, col 18.
            write(''';
    _cutoff[_i0] *= ''')
            _v = VFFSL(SL,"cutoff",True) # '${cutoff}' on line 144, col 21
            if _v is not None: write(_filter(_v, rawExpr='${cutoff}')) # from line 144, col 21.
            write(''';
''')
            if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 145, 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('''    _cutoff[_i0] *= ''')
                _v = VFFSL(SL,"cutoff",True) # '${cutoff}' on line 148, col 21
                if _v is not None: write(_filter(_v, rawExpr='${cutoff}')) # from line 148, col 21.
                write(''';
''')
            write('''  }
''')
        write('''  
''')
        #  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('''  {
    ''')
        _v = VFFSL(SL,"loopOverVectorsInBasisWithInnerContent",False)([vector], VFFSL(SL,"homeBasis",True), VFFSL(SL,"insideFindMaxErrorLoops",False)(vector)) # '${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindMaxErrorLoops(vector)), autoIndent=True}' on line 162, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideFindMaxErrorLoops(vector)), autoIndent=True}')) # from line 162, col 5.
        write('''  }
  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}) # "${insertCodeForFeatures('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}), autoIndent=True}" on line 164, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('findMax', ['Driver'], {'variable': '&_error', 'count': '1'}), autoIndent=True}")) # from line 164, col 3.
        write('''  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('timestepErrorEnd', featureOrdering, dict) # "${insertCodeForFeaturesInReverseOrder('timestepErrorEnd', featureOrdering, dict), autoIndent=True}" on line 165, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeaturesInReverseOrder('timestepErrorEnd', featureOrdering, dict), autoIndent=True}")) # from line 165, col 3.
        write('''  
  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 173, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        write('''for (long _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 175, col 27
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 175, col 27.
        write('''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 176, col 3
            modFunction = 'mod2'
        else: # generated from line 178, col 3
            modFunction = 'abs'
        write('''  _temp_mod = ''')
        _v = VFFSL(SL,"modFunction",True) # '${modFunction}' on line 181, col 15
        if _v is not None: write(_filter(_v, rawExpr='${modFunction}')) # from line 181, col 15.
        write('''(_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 181, col 31
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 181, col 31.
        write('''[_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 181, col 45
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 181, col 45.
        write('''_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 191, 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('''for (long  _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 193, col 28
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 193, col 28.
        write('''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 194, col 3
            modCutoffFunction = 'mod2'
        else: # generated from line 196, col 3
            modCutoffFunction = 'abs'
        if len(VFFSL(SL,"vector.field.dimensions",True)) > 0: # generated from line 199, col 3
            write('''  if (''')
            _v = VFFSL(SL,"modCutoffFunction",True) # '${modCutoffFunction}' on line 200, col 7
            if _v is not None: write(_filter(_v, rawExpr='${modCutoffFunction}')) # from line 200, col 7.
            write('''(_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 200, col 29
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 200, col 29.
            write('''[_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 200, col 43
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 200, col 43.
            write('''_index_pointer + _i1]) > _cutoff[_i1]) {
    ''')
            _v = VFFSL(SL,"updateMaximumError",False)(VFFSL(SL,"vector",True)) # '${updateMaximumError($vector), autoIndent=True}' on line 201, col 5
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${updateMaximumError($vector), autoIndent=True}')) # from line 201, col 5.
            write('''  }
''')
        else: # generated from line 203, col 3
            write('''  ''')
            _v = VFFSL(SL,"updateMaximumError",False)(VFFSL(SL,"vector",True)) # '${updateMaximumError($vector), autoIndent=True}' on line 204, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${updateMaximumError($vector), autoIndent=True}')) # from line 204, col 3.
        write('''}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def insideLookForNaNLoops($vector) at line 210, 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('''  for (long _i1 = 0; _i1 < _''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 218, col 29
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 218, col 29.
        write('''_ncomponents; _i1++) {
''')
        if VFFSL(SL,"vector.type",True) == 'complex': # generated from line 219, col 3
            write('''    if (_xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 220, col 28
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 220, col 28.
            write('''[_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 220, col 42
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 220, col 42.
            write('''_index_pointer + _i1].Re())
      || _xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 221, col 29
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 221, col 29.
            write('''[_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 221, col 43
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 221, col 43.
            write('''_index_pointer + _i1].Im())) bNoNaNsPresent = false;
''')
        else: # generated from line 222, col 3
            write('''    if (_xmds_isnonfinite(_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 223, col 28
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 223, col 28.
            write('''[_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 223, col 42
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 223, col 42.
            write('''_index_pointer + _i1])) bNoNaNsPresent = false;
''')
        write('''  }
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def updateMaximumError($vector) at line 229, 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('''_temp_error = abs(_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 20
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 20.
        write('''[_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 34
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 34.
        write('''_index_pointer + _i1] - _checkfield[_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 83
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 83.
        write('''_index_pointer + _i1]) / (0.5*abs(_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 130
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 130.
        write('''[_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 144
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 144.
        write('''_index_pointer + _i1]) + 0.5*abs(_checkfield[_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 231, col 202
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 231, col 202.
        write('''_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}) # "${insertCodeForFeatures('updateMaximumError', ['Diagnostics'], {'vector': vector})}" on line 242, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('updateMaximumError', ['Diagnostics'], {'vector': vector})}")) # from line 242, 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 247, 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('''bool _segment''')
        _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 249, col 14
        if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 249, col 14.
        write('''_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 249, col 31
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 249, col 31.
        write('''_reset(''')
        _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 249, col 50
        if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 249, col 50.
        write('''* _reset_to_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 249, col 76
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 249, col 76.
        write(''')
{
  ''')
        _v = VFFSL(SL,"copyVectors",False)([vector], destPrefix = '', srcPrefix = '_reset_to') # "${copyVectors([vector], destPrefix = '', srcPrefix = '_reset_to'), autoIndent=True}" on line 251, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${copyVectors([vector], destPrefix = '', srcPrefix = '_reset_to'), autoIndent=True}")) # from line 251, col 3.
        write("""  
  /* 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)) # '${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideLookForNaNLoops(vector)), autoIndent=True}' on line 256, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${loopOverVectorsInBasisWithInnerContent([vector], $homeBasis, $insideLookForNaNLoops(vector)), autoIndent=True}')) # from line 256, col 5.
        write('''  }
  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 263, 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('''real _tolerance = ''')
        _v = VFFSL(SL,"tolerance",True) # '${tolerance}' on line 269, col 19
        if _v is not None: write(_filter(_v, rawExpr='${tolerance}')) # from line 269, col 19.
        write(''';
''')
        # 
        featureOrdering = ['ErrorCheck']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('createToleranceVariable', featureOrdering) # "${insertCodeForFeatures('createToleranceVariable', featureOrdering)}" on line 272, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('createToleranceVariable', featureOrdering)}")) # from line 272, 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 276, 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('''real _step = ''')
        _v = VFFSL(SL,"interval",True) # '${interval}' on line 278, col 14
        if _v is not None: write(_filter(_v, rawExpr='${interval}')) # from line 278, col 14.
        write('''/(real)''')
        _v = VFFSL(SL,"stepCount",True) # '${stepCount}' on line 278, col 32
        if _v is not None: write(_filter(_v, rawExpr='${stepCount}')) # from line 278, col 32.
        write(''';
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) # '${createToleranceVariable}' on line 285, col 1
        if _v is not None: write(_filter(_v, rawExpr='${createToleranceVariable}')) # from line 285, col 1.
        #  Insert code for features
        featureOrderingOuter = ['Stochastic']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepBegin', featureOrderingOuter) # "${insertCodeForFeatures('integrateAdaptiveStepBegin', featureOrderingOuter)}" on line 288, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('integrateAdaptiveStepBegin', featureOrderingOuter)}")) # from line 288, col 1.
        write('''
real _error, _last_norm_error = 1.0;
''')
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 291, col 3
            write('''real _''')
            _v = VFFSL(SL,"name",True) # '${name}' on line 292, col 7
            if _v is not None: write(_filter(_v, rawExpr='${name}')) # from line 292, col 7.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 292, col 15
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 292, col 15.
            write('''_error;
''')
        write('''
bool _discard = false;
bool _break_next = false;

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

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

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

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

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

''')
        _v = VFFSL(SL,"allocate",True) # '${allocate}' on line 316, col 1
        if _v is not None: write(_filter(_v, rawExpr='${allocate}')) # from line 316, col 1.
        _v = VFFSL(SL,"initialise",True) # '${initialise}' on line 317, col 1
        if _v is not None: write(_filter(_v, rawExpr='${initialise}')) # from line 317, col 1.
        _v = VFFSL(SL,"localInitialise",True) # '${localInitialise}' on line 318, col 1
        if _v is not None: write(_filter(_v, rawExpr='${localInitialise}')) # from line 318, col 1.
        write('''
do {
''')
        featureOrderingOuterLoop = ['MaxIterations', 'Output', 'ErrorCheck']
        write('''  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop) # "${insertCodeForFeatures('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop), autoIndent=True}" on line 322, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('integrateAdaptiveStepOuterLoopBegin', featureOrderingOuterLoop), autoIndent=True}")) # from line 322, col 3.
        write('''  
  ''')
        _v = VFFSL(SL,"preSingleStep",True) # '${preSingleStep, autoIndent=True}' on line 324, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${preSingleStep, autoIndent=True}')) # from line 324, col 3.
        write('''  do {
''')
        #  Insert code for features
        featureOrderingInnerLoop = ['Stochastic']
        write('''    ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop) # "${insertCodeForFeatures('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop), autoIndent=True}" on line 328, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('integrateAdaptiveStepInnerLoopBegin', featureOrderingInnerLoop), autoIndent=True}")) # from line 328, col 5.
        write('''    
    ''')
        _v = VFN(VFFSL(SL,"stepper",True),"singleIntegrationStep",False)(function) # '${stepper.singleIntegrationStep(function), autoIndent=True}' on line 330, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${stepper.singleIntegrationStep(function), autoIndent=True}')) # from line 330, col 5.
        write('''    
    ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop) # "${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop), autoIndent=True}" on line 332, col 5
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepInnerLoopEnd', featureOrderingInnerLoop), autoIndent=True}")) # from line 332, col 5.
        write('''    
    _error = 0.0;
''')
        for vector in VFFSL(SL,"integrationVectors",True): # generated from line 335, col 3
            write('''    
    _''')
            _v = VFFSL(SL,"name",True) # '${name}' on line 337, col 6
            if _v is not None: write(_filter(_v, rawExpr='${name}')) # from line 337, col 6.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 337, col 14
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 337, col 14.
            write('''_error = _''')
            _v = VFFSL(SL,"name",True) # '${name}' on line 337, col 36
            if _v is not None: write(_filter(_v, rawExpr='${name}')) # from line 337, col 36.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 337, col 44
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 337, col 44.
            write('''_timestep_error(_''')
            _v = VFFSL(SL,"stepper.errorFieldName",True) # '${stepper.errorFieldName}' on line 337, col 73
            if _v is not None: write(_filter(_v, rawExpr='${stepper.errorFieldName}')) # from line 337, col 73.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 337, col 99
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 337, col 99.
            write(''');
    if (_''')
            _v = VFFSL(SL,"name",True) # '${name}' on line 338, col 10
            if _v is not None: write(_filter(_v, rawExpr='${name}')) # from line 338, col 10.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 338, col 18
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 338, col 18.
            write('''_error > _error)
      _error = _''')
            _v = VFFSL(SL,"name",True) # '${name}' on line 339, col 17
            if _v is not None: write(_filter(_v, rawExpr='${name}')) # from line 339, col 17.
            write('''_''')
            _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 339, col 25
            if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 339, col 25.
            write('''_error;
''')
        write('''    
    _attempted_steps++;
    
''')
        featureOrderingForToleranceChecking = ['Diagnostics', 'Stochastic']
        write('''    if (_error < _tolerance) {
      ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('adaptiveStepSucceeded', VFFSL(SL,"featureOrderingForToleranceChecking",True)) # "${insertCodeForFeatures('adaptiveStepSucceeded', $featureOrderingForToleranceChecking), autoIndent=True}" on line 346, col 7
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('adaptiveStepSucceeded', $featureOrderingForToleranceChecking), autoIndent=True}")) # from line 346, col 7.
        write('''      _''')
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 347, col 8
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 347, col 8.
        write('''_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)) # "${insertCodeForFeatures('adaptiveStepFailed', $featureOrderingForToleranceChecking), autoIndent=True}" on line 354, col 7
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('adaptiveStepFailed', $featureOrderingForToleranceChecking), autoIndent=True}")) # from line 354, col 7.
        write('''      ''')
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 355, col 7
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 355, col 7.
        write(''' -= _step;

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

        _LOG(_WARNING_LOG_LEVEL, "WARNING: NaN present. Integration halted at ''')
            _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 360, col 79
            if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 360, col 79.
            write(''' = %e.\\n"
                           "         Non-finite number in integration vector \\"''')
            _v = VFFSL(SL,"vector.name",True) # '${vector.name}' on line 361, col 80
            if _v is not None: write(_filter(_v, rawExpr='${vector.name}')) # from line 361, col 80.
            write('''\\" in segment ''')
            _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 361, col 108
            if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 361, col 108.
            write('''.\\n", ''')
            _v = VFFSL(SL,"propagationDimension",True) # '$propagationDimension' on line 361, col 130
            if _v is not None: write(_filter(_v, rawExpr='$propagationDimension')) # from line 361, col 130.
            write(''');
        ''')
            _v = VFFSL(SL,"earlyTerminationCode",True) # '${earlyTerminationCode, autoIndent=True}' on line 362, col 9
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${earlyTerminationCode, autoIndent=True}')) # from line 362, col 9.
            write('''      }
''')
        write('''
      ''')
        _v = VFN(VFFSL(SL,"functions",True)['ipEvolve'],"call",False)(_exponent = -1, parentFunction=function) # "${functions['ipEvolve'].call(_exponent = -1, parentFunction=function)}" on line 366, col 7
        if _v is not None: write(_filter(_v, rawExpr="${functions['ipEvolve'].call(_exponent = -1, parentFunction=function)}")) # from line 366, col 7.
        write('''
      
      _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) # '${integrationOrder}' on line 378, col 83
        if _v is not None: write(_filter(_v, rawExpr='${integrationOrder}')) # from line 378, col 83.
        write(''')) * pow(_last_norm_error, real(0.4/''')
        _v = VFFSL(SL,"integrationOrder",True) # '${integrationOrder}' on line 378, col 138
        if _v is not None: write(_filter(_v, rawExpr='${integrationOrder}')) # from line 378, col 138.
        write("""));
      _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) # '${integrationOrder}' on line 383, col 80
        if _v is not None: write(_filter(_v, rawExpr='${integrationOrder}')) # from line 383, col 80.
        write('''));
      }
      _old_step = _step;
      _last_norm_error = pow(_safetyFactor/_scalingFactor*pow(_last_norm_error, real(0.4/''')
        _v = VFFSL(SL,"integrationOrder",True) # '${integrationOrder}' on line 386, col 90
        if _v is not None: write(_filter(_v, rawExpr='${integrationOrder}')) # from line 386, col 90.
        write(''')), real(''')
        _v = VFFSL(SL,"integrationOrder",True) # '${integrationOrder}' on line 386, col 118
        if _v is not None: write(_filter(_v, rawExpr='${integrationOrder}')) # from line 386, col 118.
        write('''/0.7));
      _step *= _scalingFactor;
    }
    
  } while (_discard);
  ''')
        _v = VFFSL(SL,"postSingleStep",True) # '${postSingleStep, autoIndent=True}' on line 391, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${postSingleStep, autoIndent=True}')) # from line 391, col 3.
        write('''  
  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop) # "${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop), autoIndent=True}" on line 393, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepOuterLoopEnd', featureOrderingOuterLoop), autoIndent=True}")) # from line 393, col 3.
        write('''} while (!_next_sample_flag[''')
        _v = VFFSL(SL,"momentGroupCount",True) + 1 # '${momentGroupCount + 1}' on line 394, col 29
        if _v is not None: write(_filter(_v, rawExpr='${momentGroupCount + 1}')) # from line 394, col 29.
        write(''']);

''')
        _v = VFFSL(SL,"localFinalise",True) # '${localFinalise}' on line 396, col 1
        if _v is not None: write(_filter(_v, rawExpr='${localFinalise}')) # from line 396, col 1.
        _v = VFFSL(SL,"finalise",True) # '${finalise}' on line 397, col 1
        if _v is not None: write(_filter(_v, rawExpr='${finalise}')) # from line 397, col 1.
        _v = VFFSL(SL,"free",True) # '${free}' on line 398, col 1
        if _v is not None: write(_filter(_v, rawExpr='${free}')) # from line 398, col 1.
        # 
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('integrateAdaptiveStepEnd', featureOrderingOuter) # "${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepEnd', featureOrderingOuter)}" on line 400, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeaturesInReverseOrder('integrateAdaptiveStepEnd', featureOrderingOuter)}")) # from line 400, col 1.
        write('''
_LOG(_SEGMENT_LOG_LEVEL, "Segment ''')
        _v = VFFSL(SL,"segmentNumber",True) # '${segmentNumber}' on line 402, col 35
        if _v is not None: write(_filter(_v, rawExpr='${segmentNumber}')) # from line 402, col 35.
        write(''': 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('''
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('''



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

''')
        # 
        #   Function implementations
        write('''













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


    _CHEETAH__instanceInitialized = False

    _CHEETAH_version = __CHEETAH_version__

    _CHEETAH_versionTuple = __CHEETAH_versionTuple__

    _CHEETAH_genTime = __CHEETAH_genTime__

    _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__

    _CHEETAH_src = __CHEETAH_src__

    _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__

    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 https://cheetahtemplate.org/

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


