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

##################################################
## 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.743762
__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/MultiPathDriver.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 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 24, 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'''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 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(u'''for (long _i0 = ''')
        _v = VFFSL(SL,"pathLoopStart",True) # u'${pathLoopStart}' on line 32, col 17
        if _v is not None: write(_filter(_v, rawExpr=u'${pathLoopStart}')) # from line 32, col 17.
        write(u'''; _i0 < ''')
        _v = VFFSL(SL,"pathLoopEnd",True) # u'${pathLoopEnd}' on line 32, col 41
        if _v is not None: write(_filter(_v, rawExpr=u'${pathLoopEnd}')) # from line 32, col 41.
        write(u'''; _i0+=''')
        _v = VFFSL(SL,"pathLoopStep",True) # u'${pathLoopStep}' on line 32, col 62
        if _v is not None: write(_filter(_v, rawExpr=u'${pathLoopStep}')) # from line 32, col 62.
        write(u''') {
  _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 37, 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(u'''#define _n_paths ''')
        _v = VFFSL(SL,"pathCount",True) # u'${pathCount}' on line 41, col 18
        if _v is not None: write(_filter(_v, rawExpr=u'${pathCount}')) # from line 41, col 18.
        write(u'''
''')
        # 
        
        ########################################
        ## 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 52, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${insertCodeForFeatures('topLevelSequenceBegin', featureOrdering, dict), autoIndent=True}")) # from line 52, col 3.
        extraIndent = dict['extraIndent']
        write(u'''
  ''')
        _v = VFFSL(SL,"topLevelSegmentPathLoop",True) # u'${topLevelSegmentPathLoop, autoIndent=True, extraIndent=extraIndent}' on line 55, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, extraIndent=extraIndent, rawExpr=u'${topLevelSegmentPathLoop, 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 topLevelSegmentPathLoop(self, **KWS):



        ## CHEETAH: generated from @def topLevelSegmentPathLoop at line 62, 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) # u'${topLevelSequence.allocate}' on line 71, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${topLevelSequence.allocate}')) # from line 71, col 1.
        write(u'''
''')
        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 74, col 3
            _v = VFFSL(SL,"o.initialise",True) # u'${o.initialise}' on line 75, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${o.initialise}')) # from line 75, 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: _97867200 finalisationCode at line 82, col 3 in the source.
        _orig_trans_97867200 = trans
        _wasBuffering_97867200 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_97867200 = DummyTransaction()
        write = _captureCollector_97867200.response().write
        for o in VFFSL(SL,"objectsNeedingInitialisation",True): # generated from line 83, col 5
            _v = VFFSL(SL,"o.finalise",True) # u'${o.finalise}' on line 84, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${o.finalise}')) # from line 84, col 1.
        write(u'''
''')
        _v = VFFSL(SL,"topLevelSequence.free",True) # u'${topLevelSequence.free}' on line 87, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${topLevelSequence.free}')) # from line 87, col 1.
        trans = _orig_trans_97867200
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_97867200 
        finalisationCode = _captureCollector_97867200.response().getvalue()
        del _orig_trans_97867200
        del _captureCollector_97867200
        del _wasBuffering_97867200
        write(u'''
''')
        _v = VFFSL(SL,"segment0_loop",True) # u'${segment0_loop}' on line 90, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${segment0_loop}')) # from line 90, col 1.
        write(u'''
  
''')
        for mg in VFFSL(SL,"momentGroups",True): # generated from line 92, col 3
            write(u'''  ''')
            _v = VFN(VFN(VFFSL(SL,"mg.rawVector",True),"functions",True)['initialise'],"call",False)() # u"${mg.rawVector.functions['initialise'].call(), autoIndent=True}" on line 93, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u"${mg.rawVector.functions['initialise'].call(), autoIndent=True}")) # from line 93, col 3.
        write(u'''  
  ''')
        _v = VFFSL(SL,"topLevelSequence.topLevelSequenceInnerContent",True) # u'${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}' on line 96, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${topLevelSequence.topLevelSequenceInnerContent, autoIndent=True}')) # from line 96, col 3.
        write(u'''}

''')
        #  Now clean up after all of the objects that we initialised early.
        _v = VFFSL(SL,"finalisationCode",True) # u'${finalisationCode}' on line 100, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${finalisationCode}')) # from line 100, 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 104, 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(u'''_''')
        _v = VFFSL(SL,"momentGroup.outputField.name",True) # u'${momentGroup.outputField.name}' on line 117, col 2
        if _v is not None: write(_filter(_v, rawExpr=u'${momentGroup.outputField.name}')) # from line 117, col 2.
        write(u'''_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 122, 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([u'_',str(VFFSL(SL,"fieldName",True)),u'_sd']),                           'components': ['stderr_' + componentName for componentName in processedVector.components]                          }
        dependentVariables.append(newVariableDict)
        # 
        write(u'''// Calculate the mean
_active_${vector.id}[${index}] /= (real) _n_paths;

// Calculate the standard error
_''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 170, col 2
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 170, col 2.
        write(u'''_sd[${index}] /= (real) _n_paths;
_''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 171, col 2
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 171, col 2.
        write(u'''_sd[${index}] -= _active_${vector.id}[${index}] * _active_${vector.id}[${index}];
if (_''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 172, col 6
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 172, col 6.
        write(u'''_sd[${index}] > 0.0) // UNVECTORISABLE
  _''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 173, col 4
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 173, col 4.
        write(u'''_sd[${index}] = sqrt(_''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 173, col 39
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 173, col 39.
        write(u'''_sd[${index}] / _n_paths);
else
  _''')
        _v = VFFSL(SL,"fieldName",True) # u'${fieldName}' on line 175, col 4
        if _v is not None: write(_filter(_v, rawExpr=u'${fieldName}')) # from line 175, col 4.
        write(u'''_sd[${index}] = 0.0;
''')
        # 
        if len(otherArrayNames): # generated from line 177, col 3
            write(u'''
// Calculate other means
''')
            for arrayName in VFFSL(SL,"otherArrayNames",True): # generated from line 180, col 5
                _v = VFFSL(SL,"arrayName",True) # u'${arrayName}' on line 181, col 1
                if _v is not None: write(_filter(_v, rawExpr=u'${arrayName}')) # from line 181, col 1.
                write(u'''[${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
        
        # 
        # 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(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__

    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://www.CheetahTemplate.org/

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


