#!/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
from xpdeint.CallOnceGuards import callOnceGuard

##################################################
## 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.66488
__CHEETAH_genTimestamp__ = 'Sat Oct 23 13:06:32 2021'
__CHEETAH_src__ = '/home/mattias/xmds-3.0.0/admin/staging/xmds-3.1.0/xpdeint/Stochastic/RandomVariables/PoissonianRandomVariable.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 PoissonianRandomVariable(ScriptElement):

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


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

        super(PoissonianRandomVariable, 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 poissonian 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 28, 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 poissonian noise
const real _new_var = 1.0 / (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # '${noiseVector.spatiallyIndependentVolumeElement}' on line 38, col 30
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.spatiallyIndependentVolumeElement}')) # from line 38, col 30.
        write(''' * _new_step);
const real _old_volume = (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # '${noiseVector.spatiallyIndependentVolumeElement}' on line 39, col 27
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.spatiallyIndependentVolumeElement}')) # from line 39, col 27.
        write(''' * _old_step);

''')
        ## START CAPTURE REGION: _51077032 loopString at line 41, col 3 in the source.
        _orig_trans_51077032 = trans
        _wasBuffering_51077032 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_51077032 = DummyTransaction()
        write = _captureCollector_51077032.response().write
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 43, col 5
            volumeFixup = ' * '.join('%s * (%s)' % (dimRep.stepSize, dimRep.volumePrefactor) for dimRep in nonUniformDimReps)
            varFixup = ' / (' + volumeFixup + ')'
            volumeFixup = ' * ' + volumeFixup
        else: # generated from line 47, col 5
            volumeFixup = ''
            varFixup = ''
        for componentNumber, component in enumerate(noiseVector.components): # generated from line 51, col 5
            _v = VFFSL(SL,"component",True) # '${component}' on line 52, col 1
            if _v is not None: write(_filter(_v, rawExpr='${component}')) # from line 52, col 1.
            write(''' = _new_var''')
            _v = VFFSL(SL,"varFixup",True) # '${varFixup}' on line 52, col 24
            if _v is not None: write(_filter(_v, rawExpr='${varFixup}')) # from line 52, col 24.
            write(''' * _poisplit_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 52, col 48
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 52, col 48.
            write('''(_new_step/_old_step, lrint(_old_array[_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 52, col 105
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 52, col 105.
            write('''_index_pointer + ''')
            _v = VFFSL(SL,"componentNumber",True) # '${componentNumber}' on line 52, col 139
            if _v is not None: write(_filter(_v, rawExpr='${componentNumber}')) # from line 52, col 139.
            write('''] * _old_volume''')
            _v = VFFSL(SL,"volumeFixup",True) # '${volumeFixup}' on line 52, col 172
            if _v is not None: write(_filter(_v, rawExpr='${volumeFixup}')) # from line 52, col 172.
            write('''));
''')
        trans = _orig_trans_51077032
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_51077032 
        loopString = _captureCollector_51077032.response().getvalue()
        del _orig_trans_51077032
        del _captureCollector_51077032
        del _wasBuffering_51077032
        _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # '${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 55, col 1
        if _v is not None: write(_filter(_v, rawExpr='${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 55, col 1.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def makeNoises(self, **KWS):


        """
        Return the code for the contents of the makeNoises function for
          a poissonian random variable, by which we mean a jump process.  
          Much of this is likely to change when we implement triggered filters
          to model jump processes efficiently.
        """

        ## CHEETAH: generated from @def makeNoises at line 60, 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('''const real _dVdt = ''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # '${noiseVector.spatiallyIndependentVolumeElement}' on line 70, col 20
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.spatiallyIndependentVolumeElement}')) # from line 70, col 20.
        if not noiseVector.static: # generated from line 71, col 3
            write(''' * _step''')
        write(''';
const real _var = 1.0 / _dVdt;
''')
        ## START CAPTURE REGION: _30619695 loopString at line 76, col 3 in the source.
        _orig_trans_30619695 = trans
        _wasBuffering_30619695 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_30619695 = DummyTransaction()
        write = _captureCollector_30619695.response().write
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 78, col 5
            volumeFixup = ' * '.join('%s * (%s)' % (dimRep.stepSize, dimRep.volumePrefactor) for dimRep in nonUniformDimReps)
            varFixup = ' / (' + volumeFixup + ')'
            volumeFixup = ' * ' + volumeFixup
        else: # generated from line 82, col 5
            volumeFixup = ''
            varFixup = ''
        for component in noiseVector.components: # generated from line 86, col 5
            _v = VFFSL(SL,"component",True) # '${component}' on line 87, col 1
            if _v is not None: write(_filter(_v, rawExpr='${component}')) # from line 87, col 1.
            write(''' = _var''')
            _v = VFFSL(SL,"varFixup",True) # '${varFixup}' on line 87, col 20
            if _v is not None: write(_filter(_v, rawExpr='${varFixup}')) # from line 87, col 20.
            write(''' * _poidev_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 87, col 42
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 87, col 42.
            write('''(''')
            _v = VFFSL(SL,"noiseMeanRate",True) # '${noiseMeanRate}' on line 87, col 60
            if _v is not None: write(_filter(_v, rawExpr='${noiseMeanRate}')) # from line 87, col 60.
            write(''' * _dVdt''')
            _v = VFFSL(SL,"volumeFixup",True) # '${volumeFixup}' on line 87, col 84
            if _v is not None: write(_filter(_v, rawExpr='${volumeFixup}')) # from line 87, col 84.
            write(''');
''')
        trans = _orig_trans_30619695
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_30619695 
        loopString = _captureCollector_30619695.response().getvalue()
        del _orig_trans_30619695
        del _captureCollector_30619695
        del _wasBuffering_30619695
        _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # '${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 90, col 1
        if _v is not None: write(_filter(_v, rawExpr='${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 90, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionPrototypes(self, **KWS):



        ## CHEETAH: generated from @def functionPrototypes at line 94, 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(PoissonianRandomVariable, self).functionPrototypes()
        if _v is not None: write(_filter(_v))
        # 
        noiseVector = VFFSL(SL,"parent",True)
        # 
        write('''real _poidev_''')
        _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 100, col 14
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 100, col 14.
        write('''(real xm);
real _poisplit_''')
        _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 101, col 16
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 101, col 16.
        write('''(real pp, int n);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionImplementations(self, **KWS):



        ## CHEETAH: generated from @def functionImplementations at line 105, 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(PoissonianRandomVariable, self).functionImplementations()
        if _v is not None: write(_filter(_v))
        # 
        noiseVector = VFFSL(SL,"parent",True)
        # 
        write('''real _poidev_''')
        _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 111, col 14
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 111, col 14.
        write('''(real xm)
{
  real sq, alxm, g, em, t, y;

  if (xm < 12.0) {        // Use direct method
    g = exp(-xm);
    em = -1.0;
    t = 1.0;
    // Instead of adding exponential deviates it is equivalent
    // to multiply uniform deviates.  We never actually have to
    // take the log, merely compare to the pre-computed exponential
    do {
      ++em;
      t *= ''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 124, col 12
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 124, col 12.
        write(''';
    } while (t > g);
  } else {
    // Use rejection method
    sq = sqrt(2.0*xm);
    alxm = log(xm);
    g = xm*alxm - lgamma(xm + 1.0);
    do {
      do {
        // y is a deviate from a Lorenzian comparison function
        y = tan(M_PI*''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 134, col 22
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 134, col 22.
        write(''');
        // em is y, shifted and scaled
        em = sq*y + xm;
      } while (em < 0.0);  // Reject if in regime of zero probability
      em = floor(em);      // The trick for integer-valued distributions
      t = 0.9*(1.0 + y*y)*exp(em*alxm - lgamma(em + 1.0) - g);
      // The ratio of the desired distribution to the comparison
      // function; we reject by comparing it to another uniform
      // deviate. The factor 0.9 so that t never exceeds 1.
    } while (''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 143, col 14
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 143, col 14.
        write(''' > t);
  }
  return em;
}

real _poisplit_''')
        _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 148, col 16
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 148, col 16.
        write('''(real pp, int n)
{
  /*
  Returns as a floating-point number an integer value that is a random deviate drawn from
  a binomial distribution of n trials each of probability pp, using erand48(_generator) as a source of
  uniform random deviates. This is exactly the distribution that must be sampled when a poissonian process is split over two smaller time steps
  */

  long j;
  real am, em, g, p, bnl, sq, t, y;
  static real pc, plog, pclog, en, oldg;

  // The binomial distribution is invariant under changing pp to 1-pp,
  // if we also change the answer to n minus itself; we do this at the end.
  p = (pp <= 0.5 ? pp : 1.0-pp);

  // This is the mean of the deviate to be produced.
  am = n * p;

  if (n < 25) {
    // Use the direct method while n is not too large. This can require up to 25 calls to erand48(_generator).
    bnl = 0.0;
    for (j = 1; j <= n; j++)
      if (''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 171, col 11
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 171, col 11.
        write(''' < p)
        ++bnl;
  } else if (am < 1.0) {
    // If fewer than one event is expected out of 25 or more trials, then the distribution is quite accurately Poisson. Use direct Poisson method.
    g = exp(-am);
    t = 1.0;
    for (j = 0; j <= n; j++) {
      t *= ''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 178, col 12
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 178, col 12.
        write(''';
      if (t < g)
        break;
    }
    bnl = (j <= n ? j : n);
  } else {
    en = n;
    oldg = lgamma(en + 1.0);
    pc = 1.0 - p;
    plog = log(p);
    pclog = log(pc);
    sq = sqrt(2.0*am*pc);
    // The following code should by now seem familiar: rejection method with a Lorentzian comparison function.
    do {
      do {
        y = tan(M_PI*''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 193, col 22
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 193, col 22.
        write(''');
        em = sq*y + am;
      } while (em < 0.0 || em >= (en+1.0)); // Reject.
      em = floor(em); // Trick for integer-valued distribution. 
      t = 1.2 * sq * (1.0 + y*y) * exp(oldg - lgamma(em + 1.0) - lgamma(en - em + 1.0) + em*plog + (en - em)*pclog); 
    } while (''')
        _v = VFN(VFFSL(SL,"generator",True),"zeroToOneRandomNumber",False)() # '${generator.zeroToOneRandomNumber()}' on line 198, col 14
        if _v is not None: write(_filter(_v, rawExpr='${generator.zeroToOneRandomNumber()}')) # from line 198, col 14.
        write(''' > t); // Reject. This happens about 1.5 times per deviate, on average.
    bnl = em;
  }
  if (p != pp) bnl = n - bnl; // Remember to undo the symmetry transformation.
  return bnl;
}

''')
        # 
        
        ########################################
        ## 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('''
''')
        # 
        # PoissonianRandomVariable.tmpl
        # 
        # Created by Joe Hope on 2009-08-22.
        # 
        # 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_PoissonianRandomVariable = 'writeBody'

## END CLASS DEFINITION

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


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


