#!/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.SimulationDrivers._SimulationDriver import _SimulationDriver
from xpdeint.Vectors.VectorElement import VectorElement

##################################################
## 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__ = 1413234540.777512
__CHEETAH_genTimestamp__ = 'Tue Oct 14 08:09:00 2014'
__CHEETAH_src__ = '/Users/graham/Library/XMDS/src/xmds2/admin/staging/xmds-2.2.2/xpdeint/SimulationDrivers/SimulationDriver.tmpl'
__CHEETAH_srcLastModified__ = 'Mon Nov 18 19:21: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 SimulationDriver(_SimulationDriver):

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


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

        super(SimulationDriver, 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: Default Simulation Driver at line 28, 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'''Default Simulation Driver''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionImplementations(self, **KWS):



        ## CHEETAH: generated from @def functionImplementations at line 30, 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(SimulationDriver, self).functionImplementations()
        if _v is not None: write(_filter(_v))
        # 
        _v = VFFSL(SL,"topLevelSegmentFunctionImplementation",True) # u'${topLevelSegmentFunctionImplementation}' on line 34, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${topLevelSegmentFunctionImplementation}')) # from line 34, col 1.
        write(u'''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def runningSimulationCode(self, **KWS):



        ## CHEETAH: generated from @def runningSimulationCode at line 39, 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'''_segment0();
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def topLevelSegmentFunctionImplementation(self, **KWS):



        ## CHEETAH: generated from @def topLevelSegmentFunctionImplementation at line 45, 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'''void _segment0()
{
''')
        # 
        #  And now insert the code for the features that apply in the top level sequence
        featureOrdering = ['ErrorCheck', 'Stochastic']
        dict = {'extraIndent': 0}
        write(u'''  ''')
        _v = VFFSL(SL,"insertCodeForFeatures",False)('topLevelSequenceBegin', featureOrdering, dict) # u"${insertCodeForFeatures('topLevelSequenceBegin', featureOrdering, dict), autoIndent=True}" on line 53, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('topLevelSequenceBegin', featureOrdering, dict), autoIndent=True}")) # from line 53, col 3.
        extraIndent = dict['extraIndent']
        write(u'''  ''')
        _v = VFFSL(SL,"topLevelSequence.topLevelSequenceInnerContent",True) # u'${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True, extraIndent=extraIndent}' on line 55, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, extraIndent=extraIndent, rawExpr=u'${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True, extraIndent=extraIndent}')) # from line 55, col 3.
        # 
        write(u'''  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('topLevelSequenceEnd', featureOrdering, dict) # u"${insertCodeForFeaturesInReverseOrder('topLevelSequenceEnd', featureOrdering, dict), autoIndent=True}" on line 57, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeaturesInReverseOrder('topLevelSequenceEnd', featureOrdering, dict), autoIndent=True}")) # from line 57, col 3.
        write(u'''}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def mainRoutine(self, **KWS):



        ## CHEETAH: generated from @def mainRoutine 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'''int main(int argc, char **argv)
{
  ''')
        _v = VFFSL(SL,"mainRoutineInnerContent",True) # u'${mainRoutineInnerContent, autoIndent=True}' on line 67, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${mainRoutineInnerContent, autoIndent=True}')) # from line 67, col 3.
        write(u'''  
  return 0;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def mainRoutineInnerContent(self, **KWS):



        ## CHEETAH: generated from @def mainRoutineInnerContent at line 74, 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'''#ifdef __APPLE__
  #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
{
  IOPMAssertionID _powerAssertionID = 0;
  IOReturn __io_result = IOPMAssertionCreateWithDescription(
    kIOPMAssertionTypePreventUserIdleSystemSleep,
    CFSTR("XMDS simulation \'''')
        _v = VFFSL(SL,"simulationName",True) # u'${simulationName}' on line 82, col 29
        if _v is not None: write(_filter(_v, rawExpr=u'${simulationName}')) # from line 82, col 29.
        write(u'''\' preventing user idle sleep"), // Assertion name
    NULL, // Assertion details
    NULL, // Human-readable reason
    NULL, // Localization bundle path
    (CFTimeInterval)0, // never timeout
    kIOPMAssertionTimeoutActionRelease,
    &_powerAssertionID
    );
  if (__io_result != kIOReturnSuccess) {
    _LOG(_WARNING_LOG_LEVEL, "Failed to disable user idle sleep\\n");
  }
  // Note, this power assertion is automatically released when the process quits.
}
  #endif
#endif

  
''')
        preAllocationFeatureOrdering = ['Arguments', 'Driver', 'ChunkedOutput']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('preAllocation', VFFSL(SL,"preAllocationFeatureOrdering",True)) # u"${insertCodeForFeatures('preAllocation', $preAllocationFeatureOrdering)}" on line 100, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('preAllocation', $preAllocationFeatureOrdering)}")) # from line 100, col 1.
        write(u'''  

''')
        vectors = set([v for v in VFFSL(SL,"templates",True) if isinstance(v, VectorElement)])
        _v = VFFSL(SL,"setVectorAllocSizes",False)(vectors) # u'${setVectorAllocSizes(vectors)}' on line 104, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${setVectorAllocSizes(vectors)}')) # from line 104, col 1.
        # 
        for field in VFFSL(SL,"fields",True): # generated from line 106, col 3
            _v = VFFSL(SL,"field.allocate",True) # u'${field.allocate}' on line 107, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${field.allocate}')) # from line 107, col 1.
        write(u'''
''')
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 110, col 3
            _v = VFFSL(SL,"mg.allocate",True) # u'${mg.allocate}' on line 111, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${mg.allocate}')) # from line 111, col 1.
        write(u'''
''')
        # 
        #     And now insert the code for the features that apply in the main function
        #   
        featureOrdering = ['Bing', 'Validation', 'Driver', 'OpenMP', 'Stochastic', 'TransformMultiplexer', 'Benchmark', 'Output']
        _v = VFFSL(SL,"insertCodeForFeatures",False)('mainBegin', VFFSL(SL,"featureOrdering",True)) # u"${insertCodeForFeatures('mainBegin', $featureOrdering)}" on line 118, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeatures('mainBegin', $featureOrdering)}")) # from line 118, col 1.
        write(u'''
''')
        #  This needs to be extracted into a function so that it can be indented further if necessary
        write(u'''/* Code that actually does stuff goes here */
''')
        _v = VFFSL(SL,"runningSimulationCode",True) # u'${runningSimulationCode}' on line 122, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${runningSimulationCode}')) # from line 122, col 1.
        write(u'''
''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('mainEnd', VFFSL(SL,"featureOrdering",True)) # u"${insertCodeForFeaturesInReverseOrder('mainEnd', $featureOrdering)}" on line 124, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${insertCodeForFeaturesInReverseOrder('mainEnd', $featureOrdering)}")) # from line 124, col 1.
        # 
        for field in VFFSL(SL,"fields",True): # generated from line 126, col 3
            _v = VFFSL(SL,"field.free",True) # u'${field.free}' on line 127, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${field.free}')) # from line 127, col 1.
        write(u'''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def setVectorAllocSizes(self, vectors, **KWS):



        ## CHEETAH: generated from @def setVectorAllocSizes($vectors) at line 133, col 1.
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        # 
        for vector in vectors: # generated from line 135, col 3
            for basis in vector.basesNeeded: # generated from line 136, col 5
                _v = VFFSL(SL,"vector.allocSize",True) # u'${vector.allocSize}' on line 137, col 1
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.allocSize}')) # from line 137, col 1.
                write(u''' = MAX(''')
                _v = VFFSL(SL,"vector.allocSize",True) # u'${vector.allocSize}' on line 137, col 27
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.allocSize}')) # from line 137, col 27.
                write(u''', ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"sizeInBasis",False)(basis) # u'${vector.field.sizeInBasis(basis)}' on line 137, col 48
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.field.sizeInBasis(basis)}')) # from line 137, col 48.
                write(u''' * _''')
                _v = VFFSL(SL,"vector.id",True) # u'${vector.id}' on line 137, col 86
                if _v is not None: write(_filter(_v, rawExpr=u'${vector.id}')) # from line 137, col 86.
                write(u'''_ncomponents);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def mainBegin(self, dict, **KWS):



        ## CHEETAH: generated from @def mainBegin($dict) at line 143, 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
        
        # 
        initialisedDimRepArrays = set()
        # 
        for field in VFFSL(SL,"fields",True): # generated from line 147, col 3
            # 
            for dim in field.dimensions: # generated from line 149, col 5
                for dimRep in [dimRep for dimRep in dim.representations if dimRep and not dimRep.arrayName in initialisedDimRepArrays]: # generated from line 150, col 7
                    _v = VFFSL(SL,"dimRep.initialiseArray",True) # u'${dimRep.initialiseArray}' on line 151, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.initialiseArray}')) # from line 151, col 1.
                    initialisedDimRepArrays.add(dimRep.arrayName)
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 156, col 3
            _v = VFFSL(SL,"mg.outputField.initialise",True) # u'${mg.outputField.initialise}' on line 157, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${mg.outputField.initialise}')) # from line 157, col 1.
        # 
        
        ########################################
        ## 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
        
        # 
        # SimulationDriver.tmpl
        # 
        # Created by Graham Dennis on 2008-02-27
        # Modified by Liam Madge on 2013-09-11
        # Modified by Gregory Bogomiagkov on 2013-09-12
        # 
        # Copyright (c) 2008-2012, Graham Dennis
        # 
        # This program is free software: you can redistribute it and/or modify
        # it under the terms of the GNU General Public License as published by
        # the Free Software Foundation, either version 2 of the License, or
        # (at your option) any later version.
        # 
        # This program is distributed in the hope that it will be useful,
        # but WITHOUT ANY WARRANTY; without even the implied warranty of
        # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        # GNU General Public License for more details.
        # 
        # You should have received a copy of the GNU General Public License
        # along with this program.  If not, see <http://www.gnu.org/licenses/>.
        # 
        write(u'''









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


    _CHEETAH__instanceInitialized = False

    _CHEETAH_version = __CHEETAH_version__

    _CHEETAH_versionTuple = __CHEETAH_versionTuple__

    _CHEETAH_genTime = __CHEETAH_genTime__

    _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__

    _CHEETAH_src = __CHEETAH_src__

    _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__

    _mainCheetahMethod_for_SimulationDriver= 'writeBody'

## END CLASS DEFINITION

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


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


