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

##################################################
## 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__ = 1413234540.683248
__CHEETAH_genTimestamp__ = 'Tue Oct 14 08:09:00 2014'
__CHEETAH_src__ = '/Users/graham/Library/XMDS/src/xmds2/admin/staging/xmds-2.2.2/xpdeint/SimulationDrivers/DistributedMPIDriver.tmpl'
__CHEETAH_srcLastModified__ = 'Thu Nov 14 17:42:09 2013'
__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 24, 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(u'''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 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(u'''  ''')
        _v = VFFSL(SL,"distributedTransform.setLocalLatticeAndOffsetVariables",True) # u'${distributedTransform.setLocalLatticeAndOffsetVariables, autoIndent=True}' on line 28, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${distributedTransform.setLocalLatticeAndOffsetVariables, autoIndent=True}')) # from line 28, col 3.
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def mainRoutine(self, **KWS):



        ## CHEETAH: generated from @def mainRoutine at line 32, 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(u'''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) # u'${mainRoutineInnerContent, autoIndent=True}' on line 40, col 3
        if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${mainRoutineInnerContent, autoIndent=True}')) # from line 40, col 3.
        write(u'''  
  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 49, 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) # u'${distributedTransform.setVectorAllocSizes(vectors)}' on line 53, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${distributedTransform.setVectorAllocSizes(vectors)}')) # from line 53, 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 57, 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 64, col 3
            if not (field.isDistributed and not vector.field.isDistributed): # generated from line 65, 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([u'_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.iterkeys(): # generated from line 74, col 5
                if vector.field in indexOverrides[dimRepName]: # generated from line 75, col 7
                    dimReps = [dimRep for dimRep in vector.field.inBasis(basis) if dimRep.canonicalName == dimRepName]
                    if not dimReps: # generated from line 77, col 9
                        continue
                    assert len(dimReps) == 1
                    vectorDimRep = dimReps[0]
                    indexOverride = indexOverrides[dimRepName][vector.field]
                    arrayName = ''.join([str(VFFSL(SL,"arrayName",True)),u' + ',str(VFFSL(SL,"indexOverride",True)),u' * ',str(VFN(VFFSL(SL,"vector.field",True),"localPointsInDimensionsAfterDimRepInBasis",False)(vectorDimRep, basis)),u' * _',str(VFFSL(SL,"vector.id",True)),u'_ncomponents'])
                    size = size + ' / ' + vectorDimRep.localLattice
            write(u'''MPI_Allreduce(MPI_IN_PLACE, ''')
            _v = VFFSL(SL,"arrayName",True) # u'$arrayName' on line 87, col 29
            if _v is not None: write(_filter(_v, rawExpr=u'$arrayName')) # from line 87, col 29.
            write(u''', ''')
            _v = VFFSL(SL,"size",True) # u'$size' on line 87, col 41
            if _v is not None: write(_filter(_v, rawExpr=u'$size')) # from line 87, col 41.
            write(u''',
              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 93, 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(u'''MPI_Allreduce(MPI_IN_PLACE, ''')
        _v = VFFSL(SL,"variable",True) # u'$variable' on line 99, col 29
        if _v is not None: write(_filter(_v, rawExpr=u'$variable')) # from line 99, col 29.
        write(u''', ''')
        _v = VFFSL(SL,"count",True) # u'$count' on line 99, col 40
        if _v is not None: write(_filter(_v, rawExpr=u'$count')) # from line 99, col 40.
        write(u''', MPI_''')
        _v = VFFSL(SL,"type",True) # u'${type}' on line 99, col 52
        if _v is not None: write(_filter(_v, rawExpr=u'${type}')) # from line 99, col 52.
        write(u''', MPI_''')
        _v = VFFSL(SL,"op",True) # u'${op}' on line 99, col 65
        if _v is not None: write(_filter(_v, rawExpr=u'${op}')) # from line 99, col 65.
        write(u''', 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 104, 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(u'''// 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 113, 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(u'''}
''')
        if not all([field.hasDimensionName(dimName) for dimName in VFFSL(SL,"distributedDimensionNames",True)]): # generated from line 122, 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(u"""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 130, col 3
            write(u'''  _sending_var = ''')
            _v = VFFSL(SL,"shadowVariable",True) # u'$shadowVariable' on line 131, col 18
            if _v is not None: write(_filter(_v, rawExpr=u'$shadowVariable')) # from line 131, col 18.
            write(u''';
  MPI_Ssend(&_sending_var, sizeof(ptrdiff_t), MPI_BYTE, 0, 0, MPI_COMM_WORLD);
''')
        write(u'''  
''')
        #  Note that a variable corresponds to an array with given component names
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 136, col 3
            write(u'''  _sending_var = ''')
            _v = VFN(VFFSL(SL,"variable.vector",True),"sizeInBasisInReals",False)(basis) # u'${variable.vector.sizeInBasisInReals(basis)}' on line 137, col 18
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.vector.sizeInBasisInReals(basis)}')) # from line 137, col 18.
            write(u''';
  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) # u'${variable.arrayName}' on line 141, col 13
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 141, col 13.
            write(u''', ''')
            _v = VFN(VFFSL(SL,"variable.vector",True),"sizeInBasisInReals",False)(basis) # u'${variable.vector.sizeInBasisInReals(basis)}' on line 141, col 36
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.vector.sizeInBasisInReals(basis)}')) # from line 141, col 36.
            write(u''', MPI_REAL, 0, 0, MPI_COMM_WORLD);
  
''')
        write(u'''_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 151, 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 156, 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 161, col 3
            write(u'''ptrdiff_t _my''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 162, col 14
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 162, col 14.
            write(u''' = ''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 162, col 34
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 162, col 34.
            write(u''';
''')
        # 
        write(u'''
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 166, col 3
            _v = VFFSL(SL,"variable.vector.type",True) # u'${variable.vector.type}' on line 167, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.vector.type}')) # from line 167, col 1.
            write(u'''* _local''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 167, col 32
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 167, col 32.
            write(u''';
''')
            _v = VFFSL(SL,"variable.vector.type",True) # u'${variable.vector.type}' on line 168, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.vector.type}')) # from line 168, col 1.
            write(u'''* _backup''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 168, col 33
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 168, col 33.
            write(u''' = ''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 168, col 57
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 168, col 57.
            write(u''';
''')
        write(u'''
for (long _dataForRank = 0; _dataForRank < _size; _dataForRank++) {
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 172, col 3
            write(u'''  ptrdiff_t ''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 173, col 13
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 173, col 13.
            write(u''';
''')
        write(u'''  ptrdiff_t _local_vector_size;
  
  if (_dataForRank == 0) {
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 178, col 3
            write(u'''    ''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 179, col 5
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 179, col 5.
            write(u''' = _my''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 179, col 28
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 179, col 28.
            write(u''';
''')
        write(u'''    
  } else {
    MPI_Status status;
''')
        for shadowVariable in VFFSL(SL,"shadowedVariablesForField",False)(field): # generated from line 184, col 3
            write(u'''    MPI_Recv(&''')
            _v = VFFSL(SL,"shadowVariable",True) # u'${shadowVariable}' on line 185, col 15
            if _v is not None: write(_filter(_v, rawExpr=u'${shadowVariable}')) # from line 185, col 15.
            write(u''', sizeof(ptrdiff_t), MPI_BYTE, _dataForRank, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
''')
        write(u'''    
    // Now allocate the space needed locally, and receive the entire buffer
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 189, col 3
            write(u'''    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) # u'${variable.arrayName}' on line 194, col 11
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 194, col 11.
            write(u''' = (''')
            _v = VFFSL(SL,"variable.vector.type",True) # u'${variable.vector.type}' on line 194, col 36
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.vector.type}')) # from line 194, col 36.
            write(u'''*) xmds_malloc(sizeof(real) * _local_vector_size);
    MPI_Recv(_local''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 195, col 20
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 195, col 20.
            write(u''', _local_vector_size,
             MPI_REAL, _dataForRank, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
    ''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 197, col 5
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 197, col 5.
            write(u''' = _local''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 197, col 35
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 197, col 35.
            write(u''';
    
''')
        write(u'''  }
''')
        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 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
        
        # 
        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 211, col 3
            #  If we don't have all the MPI dimensions, then the data will be local.
            return
        # 
        write(u'''  
  if (_dataForRank != 0) {
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 218, col 3
            write(u'''    xmds_free(_local''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 219, col 21
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 219, col 21.
            write(u''');
''')
        write(u'''  }
} // End looping over ranks
''')
        for variable in VFFSL(SL,"dependentVariables",True): # generated from line 223, col 3
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 224, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 224, col 1.
            write(u''' = _backup''')
            _v = VFFSL(SL,"variable.arrayName",True) # u'${variable.arrayName}' on line 224, col 32
            if _v is not None: write(_filter(_v, rawExpr=u'${variable.arrayName}')) # from line 224, col 32.
            write(u''';
''')
        write(u'''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def writeDataHDF5ModifyLoopContents($dict) at line 230, 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 237, col 3
            return
        # 
        writeLoopContents = dict['writeLoopContents']
        ## START CAPTURE REGION: _51336368 newWriteLoopContents at line 242, col 3 in the source.
        _orig_trans_51336368 = trans
        _wasBuffering_51336368 = self._CHEETAH__isBuffering
        self._CHEETAH__isBuffering = True
        trans = _captureCollector_51336368 = DummyTransaction()
        write = _captureCollector_51336368.response().write
        for fileDimIndex, memDimIndex, dimRep in dimRepOrdering: # generated from line 243, col 5
            write(u'''hsize_t file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 244, col 20
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 244, col 20.
            write(u''' = file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # u'$fileDimIndex' on line 244, col 48
            if _v is not None: write(_filter(_v, rawExpr=u'$fileDimIndex')) # from line 244, col 48.
            write(u'''];
hsize_t mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 245, col 19
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 245, col 19.
            write(u''' = mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 245, col 46
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 245, col 46.
            write(u'''];
hsize_t count_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 246, col 15
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 246, col 15.
            write(u''' = mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 246, col 42
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 246, col 42.
            write(u'''];
mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 247, col 11
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 247, col 11.
            write(u'''] = 1;

''')
        # 
        _v = VFFSL(SL,"hdf5DataCopyLoops",False)(dimRepOrdering[:], writeLoopContents) # u'${hdf5DataCopyLoops(dimRepOrdering[:], writeLoopContents)}' on line 251, col 1
        if _v is not None: write(_filter(_v, rawExpr=u'${hdf5DataCopyLoops(dimRepOrdering[:], writeLoopContents)}')) # from line 251, col 1.
        for fileDimIndex, memDimIndex, dimRep in dimRepOrdering: # generated from line 252, col 5
            write(u'''
file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # u'$fileDimIndex' on line 254, col 12
            if _v is not None: write(_filter(_v, rawExpr=u'$fileDimIndex')) # from line 254, col 12.
            write(u'''] = file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 254, col 40
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 254, col 40.
            write(u''';
mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 255, col 11
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 255, col 11.
            write(u'''] = mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 255, col 37
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 255, col 37.
            write(u''';
mem_count[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 256, col 11
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 256, col 11.
            write(u'''] = count_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 256, col 33
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 256, col 33.
            write(u''';
''')
        trans = _orig_trans_51336368
        write = trans.response().write
        self._CHEETAH__isBuffering = _wasBuffering_51336368 
        newWriteLoopContents = _captureCollector_51336368.response().getvalue()
        del _orig_trans_51336368
        del _captureCollector_51336368
        del _wasBuffering_51336368
        # 
        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 264, 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 265, col 3
            _v = VFFSL(SL,"writeLoopContents",True) # u'${writeLoopContents}' on line 266, col 1
            if _v is not None: write(_filter(_v, rawExpr=u'${writeLoopContents}')) # from line 266, col 1.
        else: # generated from line 267, col 3
            fileDimIndex, memDimIndex, dimRep = remainingDimReps.pop(0)
            write(u'''for (hsize_t _i''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 269, col 16
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 269, col 16.
            write(u''' = 0; _i''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 269, col 38
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 269, col 38.
            write(u''' < count_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 269, col 61
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 269, col 61.
            write(u'''; _i''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 269, col 79
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 269, col 79.
            write(u'''++) {
  file_start[''')
            _v = VFFSL(SL,"fileDimIndex",True) # u'$fileDimIndex' on line 270, col 14
            if _v is not None: write(_filter(_v, rawExpr=u'$fileDimIndex')) # from line 270, col 14.
            write(u'''] = file_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 270, col 42
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 270, col 42.
            write(u''' + _i''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 270, col 61
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 270, col 61.
            write(u''';
  mem_start[''')
            _v = VFFSL(SL,"memDimIndex",True) # u'$memDimIndex' on line 271, col 13
            if _v is not None: write(_filter(_v, rawExpr=u'$memDimIndex')) # from line 271, col 13.
            write(u'''] = mem_start_''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 271, col 39
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 271, col 39.
            write(u''' + _i''')
            _v = VFFSL(SL,"dimRep.name",True) # u'${dimRep.name}' on line 271, col 58
            if _v is not None: write(_filter(_v, rawExpr=u'${dimRep.name}')) # from line 271, col 58.
            write(u''';
  
  ''')
            _v = VFFSL(SL,"hdf5DataCopyLoops",False)(remainingDimReps, writeLoopContents) # u'${hdf5DataCopyLoops(remainingDimReps, writeLoopContents), autoIndent=True}' on line 273, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr=u'${hdf5DataCopyLoops(remainingDimReps, writeLoopContents), autoIndent=True}')) # from line 273, col 3.
            write(u'''}
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def evaluateNoiseVectorBegin($dict) at line 278, 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 282, 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(u"""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 298, 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 302, col 3
            #  If the field is distributed, then the noise
            #  will need to vary along the MPI dimension, so all is
            #  OK.
            return
        # 
        write(u'''}
// Broadcast the noises to other nodes
MPI_Bcast(_active_''')
        _v = VFFSL(SL,"noiseVector.id",True) # u'${noiseVector.id}' on line 311, col 19
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.id}')) # from line 311, col 19.
        write(u''', ''')
        _v = VFN(VFFSL(SL,"noiseVector",True),"sizeInBasisInReals",False)(noiseVector.initialBasis) # u'${noiseVector.sizeInBasisInReals(noiseVector.initialBasis)}' on line 311, col 38
        if _v is not None: write(_filter(_v, rawExpr=u'${noiseVector.sizeInBasisInReals(noiseVector.initialBasis)}')) # from line 311, col 38.
        write(u''', 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 317, 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(u'''// Only generate random seeds on the first rank, then distribute to all.
unsigned long _local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 322, col 22
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 322, col 22.
        write(u'''_seeds[''')
        _v = VFFSL(SL,"generator.seedCount",True) # u'${generator.seedCount}' on line 322, col 55
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.seedCount}')) # from line 322, col 55.
        write(u'''];
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 328, 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(u'''  for (int _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"generator.seedCount",True) # u'${generator.seedCount}' on line 332, col 27
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.seedCount}')) # from line 332, col 27.
        write(u'''; _i0++)
      _local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 333, col 14
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 333, col 14.
        write(u'''_seeds[_i0] = (unsigned long)''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 333, col 69
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 333, col 69.
        write(u'''_seeds[_i0];
}
// Broadcast seeds to other nodes
MPI_Bcast(_local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 336, col 18
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 336, col 18.
        write(u'''_seeds, ''')
        _v = VFFSL(SL,"generator.seedCount",True) # u'${generator.seedCount}' on line 336, col 52
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.seedCount}')) # from line 336, col 52.
        write(u''', MPI_UNSIGNED_LONG, 0, MPI_COMM_WORLD);
// Copy to the correct array
for (int _i0 = 0; _i0 < ''')
        _v = VFFSL(SL,"generator.seedCount",True) # u'${generator.seedCount}' on line 338, col 25
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.seedCount}')) # from line 338, col 25.
        write(u'''; _i0++)
    ''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 339, col 5
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 339, col 5.
        write(u'''_seeds[_i0] = (uint32_t)_local_''')
        _v = VFFSL(SL,"generator.generatorName",True) # u'${generator.generatorName}' on line 339, col 62
        if _v is not None: write(_filter(_v, rawExpr=u'${generator.generatorName}')) # from line 339, col 62.
        write(u'''_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 344, 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(u'''// 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
        
        # 
        # 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(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_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 http://www.CheetahTemplate.org/

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


