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

##################################################
## 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__ = 1634954793.0377693
__CHEETAH_genTimestamp__ = 'Sat Oct 23 13:06:33 2021'
__CHEETAH_src__ = '/home/mattias/xmds-3.0.0/admin/staging/xmds-3.1.0/xpdeint/SimulationDrivers/DistributedMPIDriver.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 DistributedMPIDriver(_DistributedMPIDriver):

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


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

        super(DistributedMPIDriver, 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: Distributed MPI Simulation Driver 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
        
        write('''Distributed MPI Simulation Driver''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def preAllocation(self, dict, **KWS):



        ## CHEETAH: generated from @def preAllocation($dict) 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
        
        # 
        write('''  ''')
        _v = VFFSL(SL,"distributedTransform.setLocalLatticeAndOffsetVariables",True) # '${distributedTransform.setLocalLatticeAndOffsetVariables, autoIndent=True}' on line 30, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${distributedTransform.setLocalLatticeAndOffsetVariables, autoIndent=True}')) # from line 30, col 3.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def mainRoutine(self, **KWS):



        ## CHEETAH: generated from @def mainRoutine 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('''int main(int argc, char **argv)
{
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD, &_size);
  MPI_Comm_rank(MPI_COMM_WORLD, &_rank);

  ''')
        _v = VFFSL(SL,"mainRoutineInnerContent",True) # '${mainRoutineInnerContent, autoIndent=True}' on line 42, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${mainRoutineInnerContent, autoIndent=True}')) # from line 42, col 3.
        write('''  
  MPI_Finalize();
  
  return 0;
}
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def setVectorAllocSizes(self, vectors, **KWS):



        ## CHEETAH: generated from @def setVectorAllocSizes($vectors) at line 51, 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(DistributedMPIDriver, self).setVectorAllocSizes(vectors)
        if _v is not None: write(_filter(_v))
        # 
        _v = VFN(VFFSL(SL,"distributedTransform",True),"setVectorAllocSizes",False)(vectors) # '${distributedTransform.setVectorAllocSizes(vectors)}' on line 55, col 1
        if _v is not None: write(_filter(_v, rawExpr='${distributedTransform.setVectorAllocSizes(vectors)}')) # from line 55, col 1.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def loopOverFieldInBasisWithVectorsAndInnerContentEnd(self, dict, **KWS):



        ## CHEETAH: generated from @def loopOverFieldInBasisWithVectorsAndInnerContentEnd($dict) at line 59, 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
        
        # 
        vectorOverrides = dict['vectorOverrides']
        indexOverrides = dict['indexOverrides']
        field = dict['field']
        basis = dict['basis']
        # 
        for vector in VFFSL(SL,"vectorOverrides",True): # generated from line 66, col 3
            if not (field.isDistributed and not vector.field.isDistributed): # generated from line 67, col 5
                #  If we aren't integrating over an MPI dimension, then everything is as usual.
                continue
            #  We did integrate over the MPI dimension, so we need to run MPI_Allreduce to combine the results.
            arrayName = ''.join(['_active_',str(VFFSL(SL,"vector.id",True))])
            size = VFN(VFFSL(SL,"vector",True),"sizeInBasisInReals",False)(basis)
            # 
            #  If we have any dimension overrides, then we don't want to add up the entire field
            for dimRepName in indexOverrides.keys(): # generated from line 76, col 5
                if vector.field in indexOverrides[dimRepName]: # generated from line 77, col 7
                    dimReps = [dimRep for dimRep in vector.field.inBasis(basis) if dimRep.canonicalName == dimRepName]
                    if not dimReps: # generated from line 79, col 9
                        continue
                    assert len(dimReps) == 1
                    vectorDimRep = dimReps[0]
                    indexOverride = indexOverrides[dimRepName][vector.field]
                    arrayName = ''.join([str(VFFSL(SL,"arrayName",True)),' + ',str(VFFSL(SL,"indexOverride",True)),' * ',str(VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(vectorDimRep, basis)),' * _',str(VFFSL(SL,"vector.id",True)),'_ncomponents'])
                    size = size + ' / ' + vectorDimRep.localLattice
            write('''MPI_Allreduce(MPI_IN_PLACE, ''')
            _v = VFFSL(SL,"arrayName",True) # '$arrayName' on line 89, col 29
            if _v is not None: write(_filter(_v, rawExpr='$arrayName')) # from line 89, col 29.
            write(''', ''')
            _v = VFFSL(SL,"size",True) # '$size' on line 89, col 41
            if _v is not None: write(_filter(_v, rawExpr='$size')) # from line 89, col 41.
            write(''',
              MPI_REAL, MPI_SUM, MPI_COMM_WORLD);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def findMax(self, dict, **KWS):



        ## CHEETAH: generated from @def findMax($dict) at line 95, 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
        
        # 
        variable = dict['variable']
        count = dict['count']
        type = dict.get('type', 'real').upper()
        op = dict.get('op', 'max').upper()
        write('''MPI_Allreduce(MPI_IN_PLACE, ''')
        _v = VFFSL(SL,"variable",True) # '$variable' on line 101, col 29
        if _v is not None: write(_filter(_v, rawExpr='$variable')) # from line 101, col 29.
        write(''', ''')
        _v = VFFSL(SL,"count",True) # '$count' on line 101, col 40
        if _v is not None: write(_filter(_v, rawExpr='$count')) # from line 101, col 40.
        write(''', MPI_''')
        _v = VFFSL(SL,"type",True) # '${type}' on line 101, col 52
        if _v is not None: write(_filter(_v, rawExpr='${type}')) # from line 101, col 52.
        write(''', MPI_''')
        _v = VFFSL(SL,"op",True) # '${op}' on line 101, col 65
        if _v is not None: write(_filter(_v, rawExpr='${op}')) # from line 101, col 65.
        write(''', MPI_COMM_WORLD);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def binaryWriteOutBegin(self, dict, **KWS):



        ## CHEETAH: generated from @def binaryWriteOutBegin($dict) at line 106, 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('''// Only write to file if we are rank 0, as we cannot assume
// that the nodes have equal access to the filesystem
if (_rank == 0) {
''')
        dict['extraIndent'] += 2
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def binaryWriteOutEnd(self, dict, **KWS):



        ## CHEETAH: generated from @def binaryWriteOutEnd($dict) at line 115, 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
        
        # 
        field = dict['field']
        basis = dict['basis']
        dependentVariables = dict['dependentVariables']
        # 
        dict['extraIndent'] -= 2
        # 
        write('''}
''')
        if not all([field.hasDimensionName(dimName) for dimName in VFFSL(SL,"distributedDimensionNames",True)]): # generated from line 124, col 3
            #  If we don't have all the MPI dimensions, then the data will be local.
            return _dummyTrans and trans.response().getvalue() or ""
        write("""else {
  // We are some other rank that isn't 0, so we need to send our data to rank 0.
  ptrdiff_t _sending_var;
  
""")
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 132, col 3
            write('''  _sending_var = ''')
            _v = VFFSL(SL,"shadowVariable",True) # '$shadowVariable' on line 133, col 18
            if _v is not None: write(_filter(_v, rawExpr='$shadowVariable')) # from line 133, col 18.
            write(''';
  MPI_Ssend(&_sending_var, sizeof(ptrdiff_t), MPI_BYTE, 0, 0, MPI_COMM_WORLD);
''')
        write('''  
''')
        #  Note that a variable corresponds to an array with given component names
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 138, col 3
            write('''  _sending_var = ''')
            _v = VFN(VFFSL(SL,"variable.vector",True),"sizeInBasisInReals",False)(basis) # '${variable.vector.sizeInBasisInReals(basis)}' on line 139, col 18
            if _v is not None: write(_filter(_v, rawExpr='${variable.vector.sizeInBasisInReals(basis)}')) # from line 139, col 18.
            write(''';
  MPI_Ssend(&_sending_var, sizeof(ptrdiff_t), MPI_BYTE, 0, 0, MPI_COMM_WORLD);
  if (_sending_var == 0)
    goto _BINARY_WRITE_OUT_END;
  MPI_Ssend(''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 143, col 13
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 143, col 13.
            write(''', ''')
            _v = VFN(VFFSL(SL,"variable.vector",True),"sizeInBasisInReals",False)(basis) # '${variable.vector.sizeInBasisInReals(basis)}' on line 143, col 36
            if _v is not None: write(_filter(_v, rawExpr='${variable.vector.sizeInBasisInReals(basis)}')) # from line 143, col 36.
            write(''', MPI_REAL, 0, 0, MPI_COMM_WORLD);
  
''')
        write('''_BINARY_WRITE_OUT_END:;
}

MPI_Barrier(MPI_COMM_WORLD);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def binaryWriteOutWriteDataBegin(self, dict, **KWS):



        ## CHEETAH: generated from @def binaryWriteOutWriteDataBegin($dict) at line 153, 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
        
        # 
        field = dict['field']
        dependentVariables = dict['dependentVariables']
        # 
        if not all([field.hasDimensionName(dimName) for dimName in VFFSL(SL,"distributedDimensionNames",True)]): # generated from line 158, col 3
            #  If we don't have all the MPI dimensions, then the data will be local.
            return
        # 
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 163, col 3
            write('''ptrdiff_t _my''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 164, col 14
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 164, col 14.
            write(''' = ''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 164, col 34
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 164, col 34.
            write(''';
''')
        # 
        write('''
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 168, col 3
            _v = VFFSL(SL,"variable.vector.type",True) # '${variable.vector.type}' on line 169, col 1
            if _v is not None: write(_filter(_v, rawExpr='${variable.vector.type}')) # from line 169, col 1.
            write('''* _local''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 169, col 32
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 169, col 32.
            write(''';
''')
            _v = VFFSL(SL,"variable.vector.type",True) # '${variable.vector.type}' on line 170, col 1
            if _v is not None: write(_filter(_v, rawExpr='${variable.vector.type}')) # from line 170, col 1.
            write('''* _backup''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 170, col 33
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 170, col 33.
            write(''' = ''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 170, col 57
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 170, col 57.
            write(''';
''')
        write('''
for (long _dataForRank = 0; _dataForRank < _size; _dataForRank++) {
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 174, col 3
            write('''  ptrdiff_t ''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 175, col 13
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 175, col 13.
            write(''';
''')
        write('''  ptrdiff_t _local_vector_size;
  
  if (_dataForRank == 0) {
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 180, col 3
            write('''    ''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 181, col 5
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 181, col 5.
            write(''' = _my''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 181, col 28
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 181, col 28.
            write(''';
''')
        write('''    
  } else {
    MPI_Status status;
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 186, col 3
            write('''    MPI_Recv(&''')
            _v = VFFSL(SL,"shadowVariable",True) # '${shadowVariable}' on line 187, col 15
            if _v is not None: write(_filter(_v, rawExpr='${shadowVariable}')) # from line 187, col 15.
            write(''', sizeof(ptrdiff_t), MPI_BYTE, _dataForRank, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
''')
        write('''    
    // Now allocate the space needed locally, and receive the entire buffer
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 191, col 3
            write('''    MPI_Recv(&_local_vector_size, sizeof(ptrdiff_t), MPI_BYTE, _dataForRank, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
    if (_local_vector_size == 0)
      continue;
    
    _local''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 196, col 11
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 196, col 11.
            write(''' = (''')
            _v = VFFSL(SL,"variable.vector.type",True) # '${variable.vector.type}' on line 196, col 36
            if _v is not None: write(_filter(_v, rawExpr='${variable.vector.type}')) # from line 196, col 36.
            write('''*) xmds_malloc(sizeof(real) * _local_vector_size);
    MPI_Recv(_local''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 197, col 20
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 197, col 20.
            write(''', _local_vector_size,
             MPI_REAL, _dataForRank, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
    ''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 199, col 5
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 199, col 5.
            write(''' = _local''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 199, col 35
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 199, col 35.
            write(''';
    
''')
        write('''  }
''')
        dict['extraIndent'] += 2
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def binaryWriteOutWriteDataEnd(self, dict, **KWS):



        ## CHEETAH: generated from @def binaryWriteOutWriteDataEnd($dict) at line 207, 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
        
        # 
        field = dict['field']
        dict['extraIndent'] -= 2
        dependentVariables = dict['dependentVariables']
        # 
        if not all([field.hasDimensionName(dimName) for dimName in VFFSL(SL,"distributedDimensionNames",True)]): # generated from line 213, col 3
            #  If we don't have all the MPI dimensions, then the data will be local.
            return
        # 
        write('''  
  if (_dataForRank != 0) {
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 220, col 3
            write('''    xmds_free(_local''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 221, col 21
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 221, col 21.
            write(''');
''')
        write('''  }
} // End looping over ranks
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 225, col 3
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 226, col 1
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 226, col 1.
            write(''' = _backup''')
            _v = VFFSL(SL,"variable.arrayName",True) # '${variable.arrayName}' on line 226, col 32
            if _v is not None: write(_filter(_v, rawExpr='${variable.arrayName}')) # from line 226, col 32.
            write(''';
''')
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def writeDataHDF5ModifyLoopContents(self, dict, **KWS):



        ## CHEETAH: generated from @def writeDataHDF5ModifyLoopContents($dict) at line 232, 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
        
        # 
        dimRepOrdering = dict['dimRepOrdering']
        #  We only care about elements that are reordered
        dimRepOrdering = [(fileDimIndex, memDimIndex, dimRep)                           for fileDimIndex, memDimIndex, dimRep in dimRepOrdering if fileDimIndex != memDimIndex]
        #  If dimRepOrdering is empty, we have nothing to do
        if not dimRepOrdering: # generated from line 239, col 3
            return
        # 
        writeLoopContents = dict['writeLoopContents']
        ## START CAPTURE REGION: _93055231 newWriteLoopContents at line 244, col 3 in the source.
        _orig_trans_93055231 = trans
        _wasBuffering_93055231 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_93055231 = DummyTransaction()
        write = _captureCollector_93055231.response().write
        for fileDimIndex, memDimIndex, dimRep in dimRepOrdering: # generated from line 245, col 5
            write('''hsize_t file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 246, col 20
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 246, col 20.
            write(''' = file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # '$fileDimIndex' on line 246, col 48
            if _v is not None: write(_filter(_v, rawExpr='$fileDimIndex')) # from line 246, col 48.
            write('''];
hsize_t mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 247, col 19
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 247, col 19.
            write(''' = mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 247, col 46
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 247, col 46.
            write('''];
hsize_t count_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 248, col 15
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 248, col 15.
            write(''' = mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 248, col 42
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 248, col 42.
            write('''];
mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 249, col 11
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 249, col 11.
            write('''] = 1;

''')
        # 
        _v = VFFSL(SL,"hdf5DataCopyLoops",False)(dimRepOrdering[:], writeLoopContents) # '${hdf5DataCopyLoops(dimRepOrdering[:], writeLoopContents)}' on line 253, col 1
        if _v is not None: write(_filter(_v, rawExpr='${hdf5DataCopyLoops(dimRepOrdering[:], writeLoopContents)}')) # from line 253, col 1.
        for fileDimIndex, memDimIndex, dimRep in dimRepOrdering: # generated from line 254, col 5
            write('''
file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # '$fileDimIndex' on line 256, col 12
            if _v is not None: write(_filter(_v, rawExpr='$fileDimIndex')) # from line 256, col 12.
            write('''] = file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 256, col 40
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 256, col 40.
            write(''';
mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 257, col 11
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 257, col 11.
            write('''] = mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 257, col 37
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 257, col 37.
            write(''';
mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 258, col 11
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 258, col 11.
            write('''] = count_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 258, col 33
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 258, col 33.
            write(''';
''')
        trans = _orig_trans_93055231
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_93055231 
        newWriteLoopContents = _captureCollector_93055231.response().getvalue()
        del _orig_trans_93055231
        del _captureCollector_93055231
        del _wasBuffering_93055231
        # 
        dict['writeLoopContents'] = newWriteLoopContents
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def hdf5DataCopyLoops(self, remainingDimReps, writeLoopContents, **KWS):



        ## CHEETAH: generated from @def hdf5DataCopyLoops(remainingDimReps, writeLoopContents) at line 266, 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 not remainingDimReps: # generated from line 267, col 3
            _v = VFFSL(SL,"writeLoopContents",True) # '${writeLoopContents}' on line 268, col 1
            if _v is not None: write(_filter(_v, rawExpr='${writeLoopContents}')) # from line 268, col 1.
        else: # generated from line 269, col 3
            fileDimIndex, memDimIndex, dimRep = remainingDimReps.pop(0)
            write('''for (hsize_t _i''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 271, col 16
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 271, col 16.
            write(''' = 0; _i''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 271, col 38
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 271, col 38.
            write(''' < count_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 271, col 61
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 271, col 61.
            write('''; _i''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 271, col 79
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 271, col 79.
            write('''++) {
  file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # '$fileDimIndex' on line 272, col 14
            if _v is not None: write(_filter(_v, rawExpr='$fileDimIndex')) # from line 272, col 14.
            write('''] = file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 272, col 42
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 272, col 42.
            write(''' + _i''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 272, col 61
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 272, col 61.
            write(''';
  mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # '$memDimIndex' on line 273, col 13
            if _v is not None: write(_filter(_v, rawExpr='$memDimIndex')) # from line 273, col 13.
            write('''] = mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 273, col 39
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 273, col 39.
            write(''' + _i''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 273, col 58
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 273, col 58.
            write(''';
  
  ''')
            _v = VFFSL(SL,"hdf5DataCopyLoops",False)(remainingDimReps, writeLoopContents) # '${hdf5DataCopyLoops(remainingDimReps, writeLoopContents), autoIndent=True}' on line 275, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${hdf5DataCopyLoops(remainingDimReps, writeLoopContents), autoIndent=True}')) # from line 275, col 3.
            write('''}
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def evaluateNoiseVectorBegin(self, dict, **KWS):



        ## CHEETAH: generated from @def evaluateNoiseVectorBegin($dict) at line 280, 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 = dict['caller']
        # 
        if noiseVector.field.isDistributed: # generated from line 284, col 3
            #  If the field is distributed, then the noise
            #  will need to vary along the MPI dimension, so all is
            #  OK.
            return
        # 
        #  This means that the noise field doesn't contain the MPI dimension.
        #  As a result, the noise vector should be identical
        write("""if (_rank == 0) {
  // This noise is for a field that isn't distributed, so we should
  // make sure the noise is the same on all ranks
""")
        dict['extraIndent'] += 2
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def evaluateNoiseVectorEnd(self, dict, **KWS):



        ## CHEETAH: generated from @def evaluateNoiseVectorEnd($dict) at line 300, 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 = dict['caller']
        # 
        if noiseVector.field.isDistributed: # generated from line 304, col 3
            #  If the field is distributed, then the noise
            #  will need to vary along the MPI dimension, so all is
            #  OK.
            return
        # 
        write('''}
// Broadcast the noises to other nodes
MPI_Bcast(_active_''')
        _v = VFFSL(SL,"noiseVector.id",True) # '${noiseVector.id}' on line 313, col 19
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.id}')) # from line 313, col 19.
        write(''', ''')
        _v = VFN(VFFSL(SL,"noiseVector",True),"sizeInBasisInReals",False)(noiseVector.initialBasis) # '${noiseVector.sizeInBasisInReals(noiseVector.initialBasis)}' on line 313, col 38
        if _v is not None: write(_filter(_v, rawExpr='${noiseVector.sizeInBasisInReals(noiseVector.initialBasis)}')) # from line 313, col 38.
        write(''', MPI_REAL, 0, MPI_COMM_WORLD);

''')
        dict['extraIndent'] -= 2
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def runtimeSeedGenerationBegin(self, dict, **KWS):



        ## CHEETAH: generated from @def runtimeSeedGenerationBegin($dict) at line 319, 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
        
        # 
        generator = dict['caller']
        # 
        write('''// Only generate random seeds on the first rank, then distribute to all.
unsigned long _local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 324, col 22
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 324, col 22.
        write('''_seeds[''')
        _v = VFFSL(SL,"generator.seedCount",True) # '${generator.seedCount}' on line 324, col 55
        if _v is not None: write(_filter(_v, rawExpr='${generator.seedCount}')) # from line 324, col 55.
        write('''];
if (_rank == 0) {
''')
        dict['extraIndent'] += 2
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def runtimeSeedGenerationEnd(self, dict, **KWS):



        ## CHEETAH: generated from @def runtimeSeedGenerationEnd($dict) at line 330, 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
        
        # 
        generator = dict['caller']
        dict['extraIndent'] -= 2
        write('''  for (int _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"generator.seedCount",True) # '${generator.seedCount}' on line 334, col 27
        if _v is not None: write(_filter(_v, rawExpr='${generator.seedCount}')) # from line 334, col 27.
        write('''; _i0++)
      _local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 335, col 14
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 335, col 14.
        write('''_seeds[_i0] = (unsigned long)''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 335, col 69
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 335, col 69.
        write('''_seeds[_i0];
}
// Broadcast seeds to other nodes
MPI_Bcast(_local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 338, col 18
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 338, col 18.
        write('''_seeds, ''')
        _v = VFFSL(SL,"generator.seedCount",True) # '${generator.seedCount}' on line 338, col 52
        if _v is not None: write(_filter(_v, rawExpr='${generator.seedCount}')) # from line 338, col 52.
        write(''', MPI_UNSIGNED_LONG, 0, MPI_COMM_WORLD);
// Copy to the correct array
for (int _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"generator.seedCount",True) # '${generator.seedCount}' on line 340, col 25
        if _v is not None: write(_filter(_v, rawExpr='${generator.seedCount}')) # from line 340, col 25.
        write('''; _i0++)
    ''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 341, col 5
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 341, col 5.
        write('''_seeds[_i0] = (uint32_t)_local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # '${generator.generatorName}' on line 341, col 62
        if _v is not None: write(_filter(_v, rawExpr='${generator.generatorName}')) # from line 341, col 62.
        write('''_seeds[_i0];

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

    def openXSILFile(self, dict, **KWS):



        ## CHEETAH: generated from @def openXSILFile($dict) at line 346, 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('''// Only let rank 0 do the writing to disk
if (_rank != 0)
  return NULL;
''')
        # 
        
        ########################################
        ## 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('''
''')
        # 
        # DistributedMPIDriver.tmpl
        # 
        # Created by Graham Dennis on 2008-03-28.
        # 
        # Copyright (c) 2008-2012, Graham Dennis
        # 
        # 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_DistributedMPIDriver = 'writeBody'

## END CLASS DEFINITION

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


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


