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

##################################################
## 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.0344603
__CHEETAH_genTimestamp__ = 'Fri May  3 09:41:35 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.3.0/xpdeint/Stochastic/RandomVariables/GaussianRandomVariable.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 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 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
        
        # 
        noiseVector = VFFSL(SL,"parent",True)
        # 
        write('''// 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)') # "${noiseVector.functions['evaluate'].call(_step = '(_new_step * _old_step)/(_old_step - _new_step)')}" on line 38, col 1
        if _v is not None: write(_filter(_v, rawExpr="${noiseVector.functions['evaluate'].call(_step = '(_new_step * _old_step)/(_old_step - _new_step)')}")) # from line 38, col 1.
        write('''

''')
        #  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('''// 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='${loopOverVectorsWithInnerContentTemplate([$noiseVector], \n"""_active_${vector.id}[$index] += _old_array[$index];\n""", basis = noiseVector.initialBasis), autoIndent=True}')) # from line 47, col 1.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def makeNoises(self, **KWS):



        ## CHEETAH: generated from @def makeNoises 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
        
        #  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('''const real _var = ''')
        _v = {'complex': 0.5, 'real': 1.0}[noiseVector.type] # "${{'complex': 0.5, 'real': 1.0}[noiseVector.type]}" on line 60, col 19
        if _v is not None: write(_filter(_v, rawExpr="${{'complex': 0.5, 'real': 1.0}[noiseVector.type]}")) # from line 60, col 19.
        write(''' / (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # '${noiseVector.spatiallyIndependentVolumeElement}' on line 60, col 73
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.spatiallyIndependentVolumeElement}')) # from line 60, col 73.
        if not noiseVector.static: # generated from line 61, col 3
            write('''* _step''')
        write(''');

''')
        _v = VFFSL(SL,"makeFixedVarianceNoises",True) # '${makeFixedVarianceNoises}' on line 66, col 1
        if _v is not None: write(_filter(_v, rawExpr='${makeFixedVarianceNoises}')) # from line 66, col 1.
        # 
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 69, col 3
            ## START CAPTURE REGION: _14782621 loopString at line 70, col 5 in the source.
            _orig_trans_14782621 = trans
            _wasBuffering_14782621 = self._CHEETAH__isBuffering
            self._CHEETAH__isBuffering = True
            trans = _captureCollector_14782621 = DummyTransaction()
            write = _captureCollector_14782621.response().write
            fixupString = ' * '.join(''.join([str(VFFSL(SL,"dimRep.stepSizeArrayName",True)),'_invsqrt[',str(VFFSL(SL,"dimRep.index",True)),' + ',str(VFFSL(SL,"dimRep.localOffset",True)),']']) for dimRep in nonUniformDimReps)
            for component in noiseVector.components: # generated from line 72, col 7
                _v = VFFSL(SL,"component",True) # '${component}' on line 73, col 1
                if _v is not None: write(_filter(_v, rawExpr='${component}')) # from line 73, col 1.
                write(''' *= ''')
                _v = VFFSL(SL,"fixupString",True) # '${fixupString}' on line 73, col 17
                if _v is not None: write(_filter(_v, rawExpr='${fixupString}')) # from line 73, col 17.
                write(''';
''')
            trans = _orig_trans_14782621
            write = trans.response().write
            self._CHEETAH__isBuffering = _wasBuffering_14782621 
            loopString = _captureCollector_14782621.response().getvalue()
            del _orig_trans_14782621
            del _captureCollector_14782621
            del _wasBuffering_14782621
            _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # '${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 76, col 1
            if _v is not None: write(_filter(_v, rawExpr='${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 76, 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('''
''')
        # 
        # 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('''

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

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


