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

##################################################
## 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.2781188
__CHEETAH_genTimestamp__ = 'Fri May 17 11:02:50 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-3.0.0/xpdeint/SimulationDrivers/SimulationDriver.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 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 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
        
        write('''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 32, 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) # '${topLevelSegmentFunctionImplementation}' on line 36, col 1
        if _v is not None: write(_filter(_v, rawExpr='${topLevelSegmentFunctionImplementation}')) # from line 36, col 1.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def runningSimulationCode(self, **KWS):



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

    def topLevelSegmentFunctionImplementation(self, **KWS):



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

    def mainRoutine(self, **KWS):



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

    def mainRoutineInnerContent(self, **KWS):



        ## CHEETAH: generated from @def mainRoutineInnerContent at line 76, 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('''#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) # '${simulationName}' on line 84, col 29
        if _v is not None: write(_filter(_v, rawExpr='${simulationName}')) # from line 84, col 29.
        write('''\' 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)) # "${insertCodeForFeatures('preAllocation', $preAllocationFeatureOrdering)}" on line 102, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('preAllocation', $preAllocationFeatureOrdering)}")) # from line 102, col 1.
        write('''  

''')
        vectors = set([v for v in VFFSL(SL,"templates",True) if isinstance(v, VectorElement)])
        _v = VFFSL(SL,"setVectorAllocSizes",False)(vectors) # '${setVectorAllocSizes(vectors)}' on line 106, col 1
        if _v is not None: write(_filter(_v, rawExpr='${setVectorAllocSizes(vectors)}')) # from line 106, col 1.
        # 
        for field in VFFSL(SL,"fields",True): # generated from line 108, col 3
            _v = VFFSL(SL,"field.allocate",True) # '${field.allocate}' on line 109, col 1
            if _v is not None: write(_filter(_v, rawExpr='${field.allocate}')) # from line 109, col 1.
        write('''
''')
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 112, col 3
            _v = VFFSL(SL,"mg.allocate",True) # '${mg.allocate}' on line 113, col 1
            if _v is not None: write(_filter(_v, rawExpr='${mg.allocate}')) # from line 113, col 1.
        write('''
''')
        # 
        #     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)) # "${insertCodeForFeatures('mainBegin', $featureOrdering)}" on line 120, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeatures('mainBegin', $featureOrdering)}")) # from line 120, col 1.
        write('''
''')
        #  This needs to be extracted into a function so that it can be indented further if necessary
        write('''/* Code that actually does stuff goes here */
''')
        _v = VFFSL(SL,"runningSimulationCode",True) # '${runningSimulationCode}' on line 124, col 1
        if _v is not None: write(_filter(_v, rawExpr='${runningSimulationCode}')) # from line 124, col 1.
        write('''
''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('mainEnd', VFFSL(SL,"featureOrdering",True)) # "${insertCodeForFeaturesInReverseOrder('mainEnd', $featureOrdering)}" on line 126, col 1
        if _v is not None: write(_filter(_v, rawExpr="${insertCodeForFeaturesInReverseOrder('mainEnd', $featureOrdering)}")) # from line 126, col 1.
        # 
        for field in VFFSL(SL,"fields",True): # generated from line 128, col 3
            _v = VFFSL(SL,"field.free",True) # '${field.free}' on line 129, col 1
            if _v is not None: write(_filter(_v, rawExpr='${field.free}')) # from line 129, col 1.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def setVectorAllocSizes($vectors) at line 135, 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 137, col 3
            for basis in vector.basesNeeded: # generated from line 138, col 5
                _v = VFFSL(SL,"vector.allocSize",True) # '${vector.allocSize}' on line 139, col 1
                if _v is not None: write(_filter(_v, rawExpr='${vector.allocSize}')) # from line 139, col 1.
                write(''' = MAX(''')
                _v = VFFSL(SL,"vector.allocSize",True) # '${vector.allocSize}' on line 139, col 27
                if _v is not None: write(_filter(_v, rawExpr='${vector.allocSize}')) # from line 139, col 27.
                write(''', ''')
                _v = VFN(VFFSL(SL,"vector.field",True),"sizeInBasis",False)(basis) # '${vector.field.sizeInBasis(basis)}' on line 139, col 48
                if _v is not None: write(_filter(_v, rawExpr='${vector.field.sizeInBasis(basis)}')) # from line 139, col 48.
                write(''' * _''')
                _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 139, col 86
                if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 139, col 86.
                write('''_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 145, 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 149, col 3
            # 
            for dim in field.dimensions: # generated from line 151, col 5
                for dimRep in [dimRep for dimRep in dim.representations if dimRep and not dimRep.arrayName in initialisedDimRepArrays]: # generated from line 152, col 7
                    _v = VFFSL(SL,"dimRep.initialiseArray",True) # '${dimRep.initialiseArray}' on line 153, col 1
                    if _v is not None: write(_filter(_v, rawExpr='${dimRep.initialiseArray}')) # from line 153, col 1.
                    initialisedDimRepArrays.add(dimRep.arrayName)
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 158, col 3
            _v = VFFSL(SL,"mg.outputField.initialise",True) # '${mg.outputField.initialise}' on line 159, col 1
            if _v is not None: write(_filter(_v, rawExpr='${mg.outputField.initialise}')) # from line 159, 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
        
        write('''
''')
        # 
        # 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('''









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

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


