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

##################################################
## 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.921936
__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/Generators/DSFMTGenerator.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 DSFMTGenerator(Generator):

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


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

        super(DSFMTGenerator, 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: Generic dSFMT noise at line 33, 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('''Generic dSFMT noise''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def generatorType(self, **KWS):



        ## Generated from @def generatorType: dsfmt_t* at line 34, 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('''dsfmt_t*''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def globals(self, **KWS):



        ## CHEETAH: generated from @def globals at line 35, 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(DSFMTGenerator, self).globals()
        if _v is not None: write(_filter(_v))
        # 
        _v = VFFSL(SL,"generatorType",True) # '$generatorType' on line 39, col 1
        if _v is not None: write(_filter(_v, rawExpr='$generatorType')) # from line 39, col 1.
        write(''' ''')
        _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 39, col 16
        if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 39, col 16.
        write(''';
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    @callOnceGuard
    def static_includes(self, **KWS):



        ## CHEETAH: generated from @def static_includes at line 48, 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(DSFMTGenerator, self).static_includes()
        if _v is not None: write(_filter(_v))
        # 
        write('''#define DSFMT_DO_NOT_USE_OLD_NAMES
#if CFG_HAVE_SSE2
  #define HAVE_SSE2
#elif CFG_HAVE_ALTIVEC
  #define HAVE_ALTIVEC
#endif

#define DSFMT_MEXP 19937

#include <dSFMT/dSFMT.h>
#include <dSFMT/dSFMT.c>
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    @callOnceGuard
    def static_globals(self, **KWS):



        ## CHEETAH: generated from @def static_globals at line 67, 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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 68, col 3
            write('''// ********************************************************
//   Struct and typedef to help convert a double to two floats
union float_double {
       uint64_t u;
       uint32_t u32[2];
       double d;
       float f[2];
};

typedef union float_double float_double_t;
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    @callOnceGuard
    def static_defines(self, **KWS):



        ## CHEETAH: generated from @def static_defines at line 83, 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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 84, col 3
            write('''// defines to help convert a double to two floats
#define LOWER_FLOAT_MASK   0x00000000007fffffULL
#define UPPER_FLOAT_MASK   0x007fffff00000000ULL
#define UPPER_FLOAT_LSHIFT 3
#define EXPONENT_BITS      0x3f8000003f800000ULL
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    @callOnceGuard
    def static_functionPrototypes(self, **KWS):



        ## CHEETAH: generated from @def static_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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 95, col 3
            write('''float generate_float_close1_open2_via_dsfmt(dsfmt_t *dsfmt_array);
void generate_float_pair_close1_open2_via_dsfmt(dsfmt_t *dsfmt_array, float &f1, float &f2);
void generate_float_array_close0_open1(dsfmt_t *noise, real array[], int vector_size);
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    @callOnceGuard
    def static_functionImplementations(self, **KWS):



        ## CHEETAH: generated from @def static_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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 104, col 3
            noiseVector = VFFSL(SL,"parent.parent",True)
            write('''// Converts a double in the range [1,2) into two floats in the range [1,2)
// returns one and stores the other in reserve for the next call to this
// function.
float generate_float_close1_open2_via_dsfmt(dsfmt_t *dsfmt_array) 
{
  static float_double_t twiddle;
  // static bool bSpareNoise = false;

  // Removing optimisation because in the situation where multiple RNGs with different seeds are being used,
  // they will interfer with one another, defeating the purpose of a deterministic seed
  /* if (bSpareNoise) {
   *   bSpareNoise = false;
   *   return twiddle.f[1];
   * }
   */
  
  twiddle.d = dsfmt_genrand_close1_open2(dsfmt_array);
  twiddle.u = ((twiddle.u << UPPER_FLOAT_LSHIFT) & UPPER_FLOAT_MASK) | (twiddle.u & LOWER_FLOAT_MASK) | EXPONENT_BITS;
  // bSpareNoise = true;
  return twiddle.f[0];
}

// Returns two random floats [1,2) by generating one double and converting it 
void generate_float_pair_close1_open2_via_dsfmt(dsfmt_t *noise, float &f1, float &f2) 
{
  float_double_t twiddle;

  twiddle.d = dsfmt_genrand_close1_open2(noise);
  twiddle.u = ((twiddle.u << UPPER_FLOAT_LSHIFT) & UPPER_FLOAT_MASK) | (twiddle.u & LOWER_FLOAT_MASK) | EXPONENT_BITS;
  f1 = twiddle.f[0];
  f2 = twiddle.f[1];
}

/* Fills an array with random floats [0,1) by calling dsfmt_fill_array_close1_open2
** to fill an array half as long with doubles [1,2), then converting these to twice 
** as many floats [1,2), then subtracting one.
** This seems to be slightly faster than calling generate_float_pair_close1_open2_via_dsfmt
** over and over again.
*/
void generate_float_array_close0_open1(dsfmt_t *noise, real noiseVector[], int vector_size) {
  // We can only ask dsfmt to fill arrays that have an even number of doubles, and the
  // number of floats must therefore be divisible by four
  int padding = vector_size & 0x3;
  int num_doubles = (vector_size - padding)/2;
  float_double_t twiddle;

  if (num_doubles > dsfmt_get_min_array_size()) {
    double *array_double = new double[num_doubles];
    dsfmt_fill_array_close1_open2(noise, array_double, num_doubles);

    for (int i=0; i<num_doubles; i++) {
      twiddle.d = array_double[i];
      twiddle.u = ((twiddle.u << UPPER_FLOAT_LSHIFT) & UPPER_FLOAT_MASK) | (twiddle.u & LOWER_FLOAT_MASK) | EXPONENT_BITS;
      reinterpret_cast<real*>(noiseVector)[2*i] = twiddle.f[0] - 1.0f;
      reinterpret_cast<real*>(noiseVector)[2*i+1] = twiddle.f[1] - 1.0f;
    }
    
    // Finish up by generating the 0,1,2 or 3 numbers on the end of the noise vector
    for (int i=0; i<padding; i++)
    {
      reinterpret_cast<real*>(noiseVector)[vector_size-i] = generate_float_close1_open2_via_dsfmt(noise) - 1.0f;
    }
    delete [] array_double;
  }
  else {
    // The number of floats we need does meet the minimum of what dsfmt can provide in 
    // and array, so it by a single number at a time instead.
    for (long _i0 = 0; _i0 < vector_size; _i0++) {
      reinterpret_cast<real*>(noiseVector)[_i0] = generate_float_close1_open2_via_dsfmt(noise) - 1.0f;
    }
  }
}
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def constructArrayUniformRandomNumbers(self, **KWS):



        ## CHEETAH: generated from @def constructArrayUniformRandomNumbers at line 182, 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.parent",True)
        if VFFSL(SL,"precision",True) == 'single': # generated from line 184, col 3
            write('''generate_float_array_close0_open1(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 185, col 35
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 185, col 35.
            write(''', reinterpret_cast<real*>(_active_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 185, col 85
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 185, col 85.
            write('''), _vector_size);
''')
        else: # generated from line 186, col 3
            write('''if (!(_vector_size & 0x1) && _vector_size > dsfmt_get_min_array_size())
  dsfmt_fill_array_open_open(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 188, col 30
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 188, col 30.
            write(''', reinterpret_cast<real*>(_active_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 188, col 80
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 188, col 80.
            write('''), _vector_size);
else {
  for (long _i0 = 0; _i0 < _vector_size; _i0++) {
    reinterpret_cast<real*>(_active_''')
            _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 191, col 37
            if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 191, col 37.
            write(''')[_i0] = dsfmt_genrand_open_open(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 191, col 87
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 191, col 87.
            write(''');
  }
}
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def minusOneToOneRandomNumber(self, **KWS):



        ## CHEETAH: generated from @def minusOneToOneRandomNumber at line 197, 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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 198, col 3
            write('''(2.0*generate_float_close1_open2_via_dsfmt(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 199, col 44
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 199, col 44.
            write(''') - 3.0)''')
        else: # generated from line 200, col 3
            write('''(2.0*dsfmt_genrand_close1_open2(''')
            _v = VFFSL(SL,"generatorName",True) # '$generatorName' on line 201, col 33
            if _v is not None: write(_filter(_v, rawExpr='$generatorName')) # from line 201, col 33.
            write(''') - 3.0)''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def zeroToOneRandomNumber(self, **KWS):



        ## CHEETAH: generated from @def zeroToOneRandomNumber at line 205, 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
        
        if VFFSL(SL,"precision",True) == 'single': # generated from line 206, col 3
            write('''(generate_float_close1_open2_via_dsfmt(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 207, col 40
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 207, col 40.
            write(''') - 1.0)''')
        else: # generated from line 208, col 3
            write('''dsfmt_genrand_open_open(''')
            _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 209, col 25
            if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 209, col 25.
            write(''')''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def initialiseLocalSeeds(self, **KWS):



        ## CHEETAH: generated from @def initialiseLocalSeeds at line 213, 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(DSFMTGenerator, self).initialiseLocalSeeds()
        if _v is not None: write(_filter(_v))
        # 
        _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 217, col 1
        if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 217, col 1.
        write(''' = (dsfmt_t *)xmds_malloc(sizeof(dsfmt_t));
dsfmt_init_by_array(''')
        _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 218, col 21
        if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 218, col 21.
        write(''', ''')
        _v = VFFSL(SL,"generatorName",True) # '${generatorName}' on line 218, col 39
        if _v is not None: write(_filter(_v, rawExpr='${generatorName}')) # from line 218, col 39.
        write('''_local_seeds, ''')
        _v = VFFSL(SL,"seedCount",True) # '${seedCount}' on line 218, col 69
        if _v is not None: write(_filter(_v, rawExpr='${seedCount}')) # from line 218, col 69.
        write(''');
''')
        # 
        
        ########################################
        ## 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('''
''')
        # 
        # DSFMTGenerator.tmpl
        # 
        # Created by Joe Hope on 2009-08-22.
        # 
        # Copyright (c) 2009-2012, Joe Hope
        # Modified Mattias Johnsson 2012
        # 
        # 
        # 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('''



''')
        # 
        #   Static includes
        #   The callOnceGuard won't work until the same includes are gone from the stochastic feature.
        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__

    uselib = ['dsfmt']

    _mainCheetahMethod_for_DSFMTGenerator = 'writeBody'

## END CLASS DEFINITION

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


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


