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

##################################################
## 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__ = 1389652445.749136
__CHEETAH_genTimestamp__ = 'Tue Jan 14 09:34:05 2014'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.0/admin/staging/xmds-2.2.0/xpdeint/Stochastic/RandomVariables/GaussianRandomVariable.tmpl'
__CHEETAH_srcLastModified__ = 'Sat Feb  4 18:39:07 2012'
__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 GaussianRandomVariable(ScriptElement):

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


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

        super(GaussianRandomVariable, 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 splitNoise(self, function, **KWS):


        """
        Return the code to generate a new smaller gaussian noise from a previous noise.
        
        The previous noise had a time step of ``old_smallest_step`` a variable available in the C
        code, not in the template itself.
        """

        ## CHEETAH: generated from @def splitNoise($function) 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
        
        # 
        noiseVector = VFFSL(SL,"parent",True)
        # 
        write(u'''// Split a gaussian noise
''')
        #  Generate a new noise of the appropriate variance
        _v = VFN(VFN(VFFSL(SL,"noiseVector",True),"functions",True)['evaluate'],"call",False)(_step = '(_new_step * _old_step)/(_old_step - _new_step)') # u"${noiseVector.functions['evaluate'].call(_step = '(_new_step * _old_step)/(_old_step - _new_step)')}" on line 36, col 1
        if _v is not None: write(_filter(_v, rawExpr=u"${noiseVector.functions['evaluate'].call(_step = '(_new_step * _old_step)/(_old_step - _new_step)')}")) # from line 36, col 1.
        write(u'''

''')
        #  Then add the old noise.
        #  When adding the old noise, the first step is to get a pointer to the old noise itself.
        #  This pointer is called _old_${noiseVector.id}
        write(u'''// Now complete creation of the new noise.

''')
        #  Now do the actual adding. This code creates a loop over the noiseVector
        #  adding the old vector at each point.
        _v = VFFSL(SL,"loopOverVectorsWithInnerContentTemplate",False)([VFFSL(SL,"noiseVector",True)], 
"""_active_${vector.id}[$index] += _old_array[$index];
""", basis = noiseVector.initialBasis)
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${loopOverVectorsWithInnerContentTemplate([$noiseVector], \n"""_active_${vector.id}[$index] += _old_array[$index];\n""", basis = noiseVector.initialBasis), autoIndent=True}')) # from line 45, col 1.
        write(u'''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def makeNoises(self, **KWS):



        ## CHEETAH: generated from @def makeNoises at line 52, 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
        
        #  Subclasses can implement makeFixedVarianceNoises and the parent will fix up the noises.
        #    Alternatively, subclasses may implement makeNoises if they can do the entire thing correctly.
        noiseVector = VFFSL(SL,"parent",True)
        # 
        write(u'''const real _var = ''')
        _v = {'complex': 0.5, 'real': 1.0}[noiseVector.type] # u"${{'complex': 0.5, 'real': 1.0}[noiseVector.type]}" on line 58, col 19
        if _v is not None: write(_filter(_v, rawExpr=u"${{'complex': 0.5, 'real': 1.0}[noiseVector.type]}")) # from line 58, col 19.
        write(u''' / (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # u'${noiseVector.spatiallyIndependentVolumeElement}' on line 58, col 73
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.spatiallyIndependentVolumeElement}')) # from line 58, col 73.
        if not noiseVector.static: # generated from line 59, col 3
            write(u'''* _step''')
        write(u''');

''')
        _v = VFFSL(SL,"makeFixedVarianceNoises",True) # u'${makeFixedVarianceNoises}' on line 64, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${makeFixedVarianceNoises}')) # from line 64, col 1.
        # 
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 67, col 3
            ## START CAPTURE REGION: _73475261 loopString at line 68, col 5 in the source.
            _orig_trans_73475261 = trans
            _wasBuffering_73475261 = self._CHEETAH__isBuffering
            self._CHEETAH__isBuffering = True
            trans = _captureCollector_73475261 = DummyTransaction()
            write = _captureCollector_73475261.response().write
            fixupString = ' * '.join(''.join([str(VFFSL(SL,"dimRep.stepSizeArrayName",True)),u'_invsqrt[',str(VFFSL(SL,"dimRep.index",True)),u' + ',str(VFFSL(SL,"dimRep.localOffset",True)),u']']) for dimRep in nonUniformDimReps)
            for component in noiseVector.components: # generated from line 70, col 7
                _v = VFFSL(SL,"component",True) # u'${component}' on line 71, col 1
                if _v is not None: write(_filter(_v, rawExpr=u'${component}')) # from line 71, col 1.
                write(u''' *= ''')
                _v = VFFSL(SL,"fixupString",True) # u'${fixupString}' on line 71, col 17
                if _v is not None: write(_filter(_v, rawExpr=u'${fixupString}')) # from line 71, col 17.
                write(u''';
''')
            trans = _orig_trans_73475261
            write = trans.response().write
            self._CHEETAH__isBuffering = _wasBuffering_73475261 
            loopString = _captureCollector_73475261.response().getvalue()
            del _orig_trans_73475261
            del _captureCollector_73475261
            del _wasBuffering_73475261
            _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 74, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 74, 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
        
        # 
        # GaussianRandomVariable.tmpl
        # 
        # Created by Joe Hope on 2009-08-20.
        # 
        # Copyright (c) 2009-2012, Joe Hope
        # 
        # This program is free software: you can redistribute it and/or modify
        # it under the terms of the GNU General Public License as published by
        # the Free Software Foundation, either version 2 of the License, or
        # (at your option) any later version.
        # 
        # This program is distributed in the hope that it will be useful,
        # but WITHOUT ANY WARRANTY; without even the implied warranty of
        # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        # GNU General Public License for more details.
        # 
        # You should have received a copy of the GNU General Public License
        # along with this program.  If not, see <http://www.gnu.org/licenses/>.
        # 
        write(u'''

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


    _CHEETAH__instanceInitialized = False

    _CHEETAH_version = __CHEETAH_version__

    _CHEETAH_versionTuple = __CHEETAH_versionTuple__

    _CHEETAH_genTime = __CHEETAH_genTime__

    _CHEETAH_genTimestamp = __CHEETAH_genTimestamp__

    _CHEETAH_src = __CHEETAH_src__

    _CHEETAH_srcLastModified = __CHEETAH_srcLastModified__

    _mainCheetahMethod_for_GaussianRandomVariable= 'writeBody'

## END CLASS DEFINITION

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


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


