#!/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.1'
__CHEETAH_versionTuple__ = (3, 2, 1, 'final', 0)
__CHEETAH_genTime__ = 1556840495.1376424
__CHEETAH_genTimestamp__ = 'Fri May  3 09:41:35 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.3.0/xpdeint/SimulationDrivers/MultiPathDriver.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 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);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def defines(self, **KWS):



        ## CHEETAH: generated from @def defines 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
        
        # 
        _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 43, col 18
        if _v is not None: write(_filter(_v, rawExpr='${pathCount}')) # from line 43, 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 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 54, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${insertCodeForFeatures('topLevelSequenceBegin', featureOrdering, dict), autoIndent=True}")) # from line 54, col 3.
        extraIndent = dict['extraIndent']
        write('''
  ''')
        _v = VFFSL(SL,"topLevelSegmentPathLoop",True) # '${topLevelSegmentPathLoop, autoIndent=True, extraIndent=extraIndent}' on line 57, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, extraIndent=extraIndent, rawExpr='${topLevelSegmentPathLoop, 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 topLevelSegmentPathLoop(self, **KWS):



        ## CHEETAH: generated from @def topLevelSegmentPathLoop at line 64, 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 73, col 1
        if _v is not None: write(_filter(_v, rawExpr='${topLevelSequence.allocate}')) # from line 73, 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 76, col 3
            _v = VFFSL(SL,"o.initialise",True) # '${o.initialise}' on line 77, col 1
            if _v is not None: write(_filter(_v, rawExpr='${o.initialise}')) # from line 77, 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: _12851167 finalisationCode at line 84, col 3 in the source.
        _orig_trans_12851167 = trans
        _wasBuffering_12851167 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_12851167 = DummyTransaction()
        write = _captureCollector_12851167.response().write
        for o in VFFSL(SL,"objectsNeedingInitialisation",True): # generated from line 85, col 5
            _v = VFFSL(SL,"o.finalise",True) # '${o.finalise}' on line 86, col 1
            if _v is not None: write(_filter(_v, rawExpr='${o.finalise}')) # from line 86, col 1.
        write('''
''')
        _v = VFFSL(SL,"topLevelSequence.free",True) # '${topLevelSequence.free}' on line 89, col 1
        if _v is not None: write(_filter(_v, rawExpr='${topLevelSequence.free}')) # from line 89, col 1.
        trans = _orig_trans_12851167
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_12851167 
        finalisationCode = _captureCollector_12851167.response().getvalue()
        del _orig_trans_12851167
        del _captureCollector_12851167
        del _wasBuffering_12851167
        write('''
''')
        _v = VFFSL(SL,"segment0_loop",True) # '${segment0_loop}' on line 92, col 1
        if _v is not None: write(_filter(_v, rawExpr='${segment0_loop}')) # from line 92, col 1.
        write('''
  
''')
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 94, col 3
            write('''  ''')
            _v = VFN(VFN(VFFSL(SL,"mg.rawVector",True),"functions",True)['initialise'],"call",False)() # "${mg.rawVector.functions['initialise'].call(), autoIndent=True}" on line 95, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr="${mg.rawVector.functions['initialise'].call(), autoIndent=True}")) # from line 95, col 3.
        write('''  
  ''')
        _v = VFFSL(SL,"topLevelSequence.topLevelSequenceInnerContent",True) # '${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}' on line 98, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}')) # from line 98, col 3.
        write('''}

''')
        #  Now clean up after all of the objects that we initialised early.
        _v = VFFSL(SL,"finalisationCode",True) # '${finalisationCode}' on line 102, col 1
        if _v is not None: write(_filter(_v, rawExpr='${finalisationCode}')) # from line 102, 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 106, 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']
        write('''_''')
        _v = VFFSL(SL,"momentGroup.outputField.name",True) # '${momentGroup.outputField.name}' on line 119, col 2
        if _v is not None: write(_filter(_v, rawExpr='${momentGroup.outputField.name}')) # from line 119, 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 124, 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.
        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 172, col 2
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 172, col 2.
        write('''_sd[${index}] /= (real) _n_paths;
_''')
        _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 173, col 2
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 173, col 2.
        write('''_sd[${index}] -= _active_${vector.id}[${index}] * _active_${vector.id}[${index}];
if (_''')
        _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 174, col 6
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 174, col 6.
        write('''_sd[${index}] > 0.0) // UNVECTORISABLE
  _''')
        _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 175, col 4
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 175, col 4.
        write('''_sd[${index}] = sqrt(_''')
        _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 175, col 39
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 175, col 39.
        write('''_sd[${index}] / _n_paths);
else
  _''')
        _v = VFFSL(SL,"fieldName",True) # '${fieldName}' on line 177, col 4
        if _v is not None: write(_filter(_v, rawExpr='${fieldName}')) # from line 177, col 4.
        write('''_sd[${index}] = 0.0;
''')
        # 
        if len(otherArrayNames): # generated from line 179, col 3
            write('''
// Calculate other means
''')
            for arrayName in VFFSL(SL,"otherArrayNames",True): # generated from line 182, col 5
                _v = VFFSL(SL,"arrayName",True) # '${arrayName}' on line 183, col 1
                if _v is not None: write(_filter(_v, rawExpr='${arrayName}')) # from line 183, 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 http://cheetahtemplate.org/

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


