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

##################################################
## 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__ = 1484975072.845517
__CHEETAH_genTimestamp__ = 'Sat Jan 21 16:04:32 2017'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.2.3/xpdeint/Stochastic/RandomVariables/PoissonianRandomVariable.tmpl'
__CHEETAH_srcLastModified__ = 'Sun Feb 12 20:15:16 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 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 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(u'''// Split a poissonian noise
const real _new_var = 1.0 / (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # u'${noiseVector.spatiallyIndependentVolumeElement}' on line 36, col 30
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.spatiallyIndependentVolumeElement}')) # from line 36, col 30.
        write(u''' * _new_step);
const real _old_volume = (''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # u'${noiseVector.spatiallyIndependentVolumeElement}' on line 37, col 27
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.spatiallyIndependentVolumeElement}')) # from line 37, col 27.
        write(u''' * _old_step);

''')
        ## START CAPTURE REGION: _76188373 loopString at line 39, col 3 in the source.
        _orig_trans_76188373 = trans
        _wasBuffering_76188373 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_76188373 = DummyTransaction()
        write = _captureCollector_76188373.response().write
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 41, col 5
            volumeFixup = ' * '.join('%s * (%s)' % (dimRep.stepSize, dimRep.volumePrefactor) for dimRep in nonUniformDimReps)
            varFixup = ' / (' + volumeFixup + ')'
            volumeFixup = ' * ' + volumeFixup
        else: # generated from line 45, col 5
            volumeFixup = ''
            varFixup = ''
        for componentNumber, component in enumerate(noiseVector.components): # generated from line 49, col 5
            _v = VFFSL(SL,"component",True) # u'${component}' on line 50, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${component}')) # from line 50, col 1.
            write(u''' = _new_var''')
            _v = VFFSL(SL,"varFixup",True) # u'${varFixup}' on line 50, col 24
            if _v is not None: write(_filter(_v, rawExpr=u'${varFixup}')) # from line 50, col 24.
            write(u''' * _poisplit_''')
            _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 50, col 48
            if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 50, col 48.
            write(u'''(_new_step/_old_step, lrint(_old_array[_''')
            _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 50, col 105
            if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 50, col 105.
            write(u'''_index_pointer + ''')
            _v = VFFSL(SL,"componentNumber",True) # u'${componentNumber}' on line 50, col 139
            if _v is not None: write(_filter(_v, rawExpr=u'${componentNumber}')) # from line 50, col 139.
            write(u'''] * _old_volume''')
            _v = VFFSL(SL,"volumeFixup",True) # u'${volumeFixup}' on line 50, col 172
            if _v is not None: write(_filter(_v, rawExpr=u'${volumeFixup}')) # from line 50, col 172.
            write(u'''));
''')
        trans = _orig_trans_76188373
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_76188373 
        loopString = _captureCollector_76188373.response().getvalue()
        del _orig_trans_76188373
        del _captureCollector_76188373
        del _wasBuffering_76188373
        _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 53, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 53, col 1.
        write(u'''
''')
        # 
        
        ########################################
        ## 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 58, 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'''const real _dVdt = ''')
        _v = VFFSL(SL,"noiseVector.spatiallyIndependentVolumeElement",True) # u'${noiseVector.spatiallyIndependentVolumeElement}' on line 68, col 20
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.spatiallyIndependentVolumeElement}')) # from line 68, col 20.
        if not noiseVector.static: # generated from line 69, col 3
            write(u''' * _step''')
        write(u''';
const real _var = 1.0 / _dVdt;
''')
        ## START CAPTURE REGION: _32952511 loopString at line 74, col 3 in the source.
        _orig_trans_32952511 = trans
        _wasBuffering_32952511 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_32952511 = DummyTransaction()
        write = _captureCollector_32952511.response().write
        nonUniformDimReps = noiseVector.nonUniformDimReps
        if nonUniformDimReps: # generated from line 76, col 5
            volumeFixup = ' * '.join('%s * (%s)' % (dimRep.stepSize, dimRep.volumePrefactor) for dimRep in nonUniformDimReps)
            varFixup = ' / (' + volumeFixup + ')'
            volumeFixup = ' * ' + volumeFixup
        else: # generated from line 80, col 5
            volumeFixup = ''
            varFixup = ''
        for component in noiseVector.components: # generated from line 84, col 5
            _v = VFFSL(SL,"component",True) # u'${component}' on line 85, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${component}')) # from line 85, col 1.
            write(u''' = _var''')
            _v = VFFSL(SL,"varFixup",True) # u'${varFixup}' on line 85, col 20
            if _v is not None: write(_filter(_v, rawExpr=u'${varFixup}')) # from line 85, col 20.
            write(u''' * _poidev_''')
            _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 85, col 42
            if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 85, col 42.
            write(u'''(''')
            _v = VFFSL(SL,"noiseMeanRate",True) # u'${noiseMeanRate}' on line 85, col 60
            if _v is not None: write(_filter(_v, rawExpr=u'${noiseMeanRate}')) # from line 85, col 60.
            write(u''' * _dVdt''')
            _v = VFFSL(SL,"volumeFixup",True) # u'${volumeFixup}' on line 85, col 84
            if _v is not None: write(_filter(_v, rawExpr=u'${volumeFixup}')) # from line 85, col 84.
            write(u''');
''')
        trans = _orig_trans_32952511
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_32952511 
        loopString = _captureCollector_32952511.response().getvalue()
        del _orig_trans_32952511
        del _captureCollector_32952511
        del _wasBuffering_32952511
        _v = VFFSL(SL,"loopOverFieldInBasisWithVectorsAndInnerContent",False)(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString) # u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}' on line 88, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${loopOverFieldInBasisWithVectorsAndInnerContent(noiseVector.field, noiseVector.initialBasis, [noiseVector], loopString)}')) # from line 88, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def functionPrototypes(self, **KWS):



        ## CHEETAH: generated from @def functionPrototypes at line 92, 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(u'''real _poidev_''')
        _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 98, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 98, col 14.
        write(u'''(real xm);
real _poisplit_''')
        _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 99, col 16
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 99, col 16.
        write(u'''(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 103, 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(u'''real _poidev_''')
        _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 109, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 109, col 14.
        write(u'''(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)() # u'${generator.zeroToOneRandomNumber()}' on line 122, col 12
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 122, col 12.
        write(u''';
    } 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)() # u'${generator.zeroToOneRandomNumber()}' on line 132, col 22
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 132, col 22.
        write(u''');
        // 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)() # u'${generator.zeroToOneRandomNumber()}' on line 141, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 141, col 14.
        write(u''' > t);
  }
  return em;
}

real _poisplit_''')
        _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 146, col 16
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 146, col 16.
        write(u'''(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)() # u'${generator.zeroToOneRandomNumber()}' on line 169, col 11
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 169, col 11.
        write(u''' < 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)() # u'${generator.zeroToOneRandomNumber()}' on line 176, col 12
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 176, col 12.
        write(u''';
      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)() # u'${generator.zeroToOneRandomNumber()}' on line 191, col 22
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 191, col 22.
        write(u''');
        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)() # u'${generator.zeroToOneRandomNumber()}' on line 196, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.zeroToOneRandomNumber()}')) # from line 196, col 14.
        write(u''' > 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
        
        # 
        # 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(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_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 http://www.CheetahTemplate.org/

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


