#!/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._MultiPathDriver import _MultiPathDriver

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.6.post2'
__CHEETAH_versionTuple__ = (3, 2, 6, 'post', 2)
__CHEETAH_genTime__ = 1634954792.7195184
__CHEETAH_genTimestamp__ = 'Sat Oct 23 13:06:32 2021'
__CHEETAH_src__ = '/home/mattias/xmds-3.0.0/admin/staging/xmds-3.1.0/xpdeint/SimulationDrivers/MultiPathDriver.tmpl'
__CHEETAH_srcLastModified__ = 'Sun Nov 24 17:06:58 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 MultiPathDriver(_MultiPathDriver):

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


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

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

    def segment0_loop(self, **KWS):



        ## CHEETAH: generated from @def segment0_loop 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
        
        # 
        write('''for (long _i0 = ''')
        _v = VFFSL(SL,"pathLoopStart",True) # '${pathLoopStart}' on line 34, col 17
        if _v is not None: write(_filter(_v, rawExpr='${pathLoopStart}')) # from line 34, col 17.
        write('''; _i0 < ''')
        _v = VFFSL(SL,"pathLoopEnd",True) # '${pathLoopEnd}' on line 34, col 41
        if _v is not None: write(_filter(_v, rawExpr='${pathLoopEnd}')) # from line 34, col 41.
        write('''; _i0+=''')
        _v = VFFSL(SL,"pathLoopStep",True) # '${pathLoopStep}' on line 34, col 62
        if _v is not None: write(_filter(_v, rawExpr='${pathLoopStep}')) # from line 34, col 62.
        write(''') {
  _LOG(_PATH_LOG_LEVEL, "Starting path %li\\n", _i0 + 1);

''')
        if self.simulation.export_all_paths_in_use: # generated from line 37, col 3
            write('''  // export_all_paths is being used, so we need to set the current path number
  // as a global variable allowing other parts of the code to have access to it
  gPathID = _i0;
''')
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def defines(self, **KWS):



        ## CHEETAH: generated from @def defines at line 46, 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(MultiPathDriver, self).defines()
        if _v is not None: write(_filter(_v))
        # 
        write('''#define _n_paths ''')
        _v = VFFSL(SL,"pathCount",True) # '${pathCount}' on line 50, col 18
        if _v is not None: write(_filter(_v, rawExpr='${pathCount}')) # from line 50, col 18.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def topLevelSegmentFunctionImplementation(self, **KWS):



        ## CHEETAH: generated from @def topLevelSegmentFunctionImplementation at line 54, 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 61, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('topLevelSequenceBegin', featureOrdering, dict), autoIndent=True}")) # from line 61, col 3.
        extraIndent = dict['extraIndent']
        write('''
  ''')
        _v = VFFSL(SL,"topLevelSegmentPathLoop",True) # '${topLevelSegmentPathLoop, autoIndent=True, extraIndent=extraIndent}' on line 64, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, extraIndent=extraIndent, rawExpr='${topLevelSegmentPathLoop, autoIndent=True, extraIndent=extraIndent}')) # from line 64, col 3.
        write('''
  ''')
        _v = VFFSL(SL,"insertCodeForFeaturesInReverseOrder",False)('topLevelSequenceEnd', featureOrdering, dict) # "${insertCodeForFeaturesInReverseOrder('topLevelSequenceEnd', featureOrdering, dict), autoIndent=True}" on line 66, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeaturesInReverseOrder('topLevelSequenceEnd', featureOrdering, dict), autoIndent=True}")) # from line 66, col 3.
        write('''}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def topLevelSegmentPathLoop(self, **KWS):



        ## CHEETAH: generated from @def topLevelSegmentPathLoop at line 71, 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
        
        # 
        #  Now loop over anything that can be initalised early and initialise them
        #  so they don't allocate and free stuff for each path. This is done now
        #  and not before the ErrorCheck and Stochastic Features because the
        #  initialisation of IP operators will depend on the step size. It would be
        #  possible to split this up into two stages of initialisation, but that
        #  seems to me like it would be ugly.
        #  
        _v = VFFSL(SL,"topLevelSequence.allocate",True) # '${topLevelSequence.allocate}' on line 80, col 1
        if _v is not None: write(_filter(_v, rawExpr='${topLevelSequence.allocate}')) # from line 80, col 1.
        write('''
''')
        objectsNeedingInitialisation = [o for o in VFFSL(SL,"templates",True) if o.hasattr('canBeInitialisedEarly') and o.canBeInitialisedEarly]
        for o in VFFSL(SL,"objectsNeedingInitialisation",True): # generated from line 83, col 3
            _v = VFFSL(SL,"o.initialise",True) # '${o.initialise}' on line 84, col 1
            if _v is not None: write(_filter(_v, rawExpr='${o.initialise}')) # from line 84, col 1.
        # 
        #  We must capture the finalisation of all the objects we initialised
        #  to make sure they don't get finalised early. As that could lead to
        #  NULL pointer dereferences, and that is bad.
        # 
        ## START CAPTURE REGION: _64777639 finalisationCode at line 91, col 3 in the source.
        _orig_trans_64777639 = trans
        _wasBuffering_64777639 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_64777639 = DummyTransaction()
        write = _captureCollector_64777639.response().write
        for o in VFFSL(SL,"objectsNeedingInitialisation",True): # generated from line 92, col 5
            _v = VFFSL(SL,"o.finalise",True) # '${o.finalise}' on line 93, col 1
            if _v is not None: write(_filter(_v, rawExpr='${o.finalise}')) # from line 93, col 1.
        write('''
''')
        _v = VFFSL(SL,"topLevelSequence.free",True) # '${topLevelSequence.free}' on line 96, col 1
        if _v is not None: write(_filter(_v, rawExpr='${topLevelSequence.free}')) # from line 96, col 1.
        trans = _orig_trans_64777639
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_64777639 
        finalisationCode = _captureCollector_64777639.response().getvalue()
        del _orig_trans_64777639
        del _captureCollector_64777639
        del _wasBuffering_64777639
        write('''
''')
        _v = VFFSL(SL,"segment0_loop",True) # '${segment0_loop}' on line 99, col 1
        if _v is not None: write(_filter(_v, rawExpr='${segment0_loop}')) # from line 99, col 1.
        write('''

''')
        #  Note there's an exception to the moment group initialisation below:
        #  If we're using the export_all_paths options on a moment group
        #  we only want to initialise this moment group
        #  for the first path, as we're using an extra dimension to store the results for
        #  for every single path. We don't want the previous path's information be overwritten.
        #  Furthermore, since the extra dimension will be initialised on the first path, 
        #  that means that single initialisation has initialised all the paths.
        #  Finally, note that there an extra intialisation we have to take care of in this
        #  case in TopLevelSequenceElement.tmpl.
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 110, col 3
            if mg.export_all_paths: # generated from line 111, col 5
                write('''  if (gPathID == 0) {
    ''')
                _v = VFN(VFN(VFFSL(SL,"mg.rawVector",True),"functions",True)['initialise'],"call",False)() # "${mg.rawVector.functions['initialise'].call(), autoIndent=True}" on line 113, col 5
                if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${mg.rawVector.functions['initialise'].call(), autoIndent=True}")) # from line 113, col 5.
                write('''
  }
''')
            else: # generated from line 115, col 5
                write('''  ''')
                _v = VFN(VFN(VFFSL(SL,"mg.rawVector",True),"functions",True)['initialise'],"call",False)() # "${mg.rawVector.functions['initialise'].call(), autoIndent=True}" on line 116, col 3
                if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${mg.rawVector.functions['initialise'].call(), autoIndent=True}")) # from line 116, col 3.
        write('''
  ''')
        _v = VFFSL(SL,"topLevelSequence.topLevelSequenceInnerContent",True) # '${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}' on line 120, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}')) # from line 120, col 3.
        write('''}

''')
        #  Now clean up after all of the objects that we initialised early.
        _v = VFFSL(SL,"finalisationCode",True) # '${finalisationCode}' on line 124, col 1
        if _v is not None: write(_filter(_v, rawExpr='${finalisationCode}')) # from line 124, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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


        """
        This function is called by the moment group so that we can add to the template
        string that will be used to create a loop to perform the processing. The code
        that this function adds calculates the variance of the sampled variable.
        
        The passed dictionary `dict` has the following key:
          - ``caller``: The moment group which is letting us modify the template string
        
        The return value is the template string that will be added to the processing loop template.
        """

        ## CHEETAH: generated from @def insideMomentGroupProcessingNoProcessingCodeLoop(dict) at line 128, 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
        
        # 
        momentGroup = dict['caller']
        if not momentGroup.export_all_paths: # generated from line 141, col 3
            #  If we're exporting all the paths, there's no _sd vector to update since we're
            #  not calculating the means or standard errors 
            write('''_''')
            _v = VFFSL(SL,"momentGroup.outputField.name",True) # '${momentGroup.outputField.name}' on line 144, col 2
            if _v is not None: write(_filter(_v, rawExpr='${momentGroup.outputField.name}')) # from line 144, col 2.
            write('''_sd[${index}] += _active_${vector.id}[${index}] * _active_${vector.id}[${index}];''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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


        """
        This function is called by the moment group at the start of the write out function
        so that we can do any processing necessary before the sampled (and perhaps processed)
        data is written out. The code that this function adds takes account for the fact that
        the processed vectors have been adding the results for all of the paths, and now need
        to be divided by the total number of paths. And something similar needs to be done for
        the standard-error variables.
        
        The passed dictionary `dict` has the following keys:
          - ``caller``: The moment group calling us.
          - ``dependentVariables``: A list of dictionaries describing the variables that are to be written out.
            This list can be modified or added to by this function.
            
            Each of these dictionaries has the following keys:
            
            - ``vector``: The vector describing the type, field and number of components
            - ``arrayName``: The name of the array that this variable is in. e.g. ``_mg0_processed``
            - ``components``: The actual name of the components being written.
        
        The return value is the template string that will be
        """

        ## CHEETAH: generated from @def writeOutFunctionImplementationBegin(dict) at line 150, 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
        
        # 
        momentGroup = dict['caller']
        dependentVariables = dict['dependentVariables']
        fieldName = VFFSL(SL,"momentGroup.outputField.name",True)
        #  
        #  First we need to modify the variable names that will be written, and add our own.
        #  We need to change all processed vector components from 'someName' to 'mean_someName'
        #  and add a variable called 'stderr_someName'
        # 
        processedVector = VFFSL(SL,"momentGroup.processedVector",True)
        otherArrayNames = set([variable['arrayName'] for variable in VFFSL(SL,"dependentVariables",True)[1:]])
        # 
        #  Modify the original variable names to have a 'mean_' prefix, unless this moment
        #  group is using "export_all_paths" in which case we're not writing the mean
        #  but rather all the paths. In this case the stderr variable is also irrelevant
        if not momentGroup.export_all_paths: # generated from line 187, col 3
            processedVectorVariable = dependentVariables[0]
            processedVectorVariable['components'] = ['mean_' + componentName for componentName in processedVectorVariable['components']]
            # 
            newVariableDict = {'vector': processedVector,                           'arrayName': ''.join(['_',str(VFFSL(SL,"fieldName",True)),'_sd']),                           'components': ['stderr_' + componentName for componentName in processedVector.components]                          }
            dependentVariables.append(newVariableDict)
            write('''
// Calculate the mean
_active_${vector.id}[${index}] /= (real) _n_paths;

// Calculate the standard error
_''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 201, col 2
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 201, col 2.
            write('''_sd[${index}] /= (real) _n_paths;
_''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 202, col 2
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 202, col 2.
            write('''_sd[${index}] -= _active_${vector.id}[${index}] * _active_${vector.id}[${index}];
if (_''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 203, col 6
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 203, col 6.
            write('''_sd[${index}] > 0.0) // UNVECTORISABLE
  _''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 204, col 4
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 204, col 4.
            write('''_sd[${index}] = sqrt(_''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 204, col 39
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 204, col 39.
            write('''_sd[${index}] / _n_paths);
else
  _''')
            _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 206, col 4
            if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 206, col 4.
            write('''_sd[${index}] = 0.0;
''')
            # 
            if len(otherArrayNames): # generated from line 208, col 5
                write('''
// Calculate other means
''')
                for arrayName in VFFSL(SL,"otherArrayNames",True): # generated from line 211, col 7
                    _v = VFFSL(SL,"arrayName",True) # '${arrayName}' on line 212, col 1
                    if _v is not None: write(_filter(_v, rawExpr='${arrayName}')) # from line 212, col 1.
                    write('''[${index}] /= (real) _n_paths;
''')
        # 
        
        ########################################
        ## 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('''
''')
        # 
        # MultiPathDriver.tmpl
        # 
        # Created by Graham Dennis on 2008-02-01.
        # 
        # 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__

    pathLoopStart = '0'

    pathLoopStep = '1'

    pathLoopEnd = '_n_paths'

    _mainCheetahMethod_for_MultiPathDriver = 'writeBody'

## END CLASS DEFINITION

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


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


