#!/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.Vectors._VectorInitialisationFromHDF5 import _VectorInitialisationFromHDF5
from xpdeint.Geometry.SplitUniformDimensionRepresentation import SplitUniformDimensionRepresentation
from xpdeint.Geometry.NonUniformDimensionRepresentation import NonUniformDimensionRepresentation

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.1'
__CHEETAH_versionTuple__ = (3, 2, 1, 'final', 0)
__CHEETAH_genTime__ = 1556840495.8966956
__CHEETAH_genTimestamp__ = 'Fri May  3 09:41:35 2019'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.3/admin/staging/xmds-2.3.0/xpdeint/Vectors/VectorInitialisationFromHDF5.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 VectorInitialisationFromHDF5(_VectorInitialisationFromHDF5):

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


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

        super(VectorInitialisationFromHDF5, 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: Vector initialisation from a HDF5 file at line 29, 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('''Vector initialisation from a HDF5 file''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def initialiseVector(self, **KWS):



        ## CHEETAH: generated from @def initialiseVector at line 31, 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
        
        # 
        basis = VFFSL(SL,"vector.initialBasis",True)
        field = VFFSL(SL,"vector.field",True)
        dimensionOffsets = {}
        # 
        initialisationCodeBlock = VFFSL(SL,"codeBlocks",True)['initialisation']
        write('''// HDF5 initialisation has three stages.
// 1. Initialise the vector to zero.
// 2. Execute any CDATA code if there is any.
// 3. Read data from the HDF5 file.

{
  // Stage 1 of initialisation
  bzero(_active_''')
        _v = VFFSL(SL,"vector.id",True) # '${vector.id}' on line 45, col 17
        if _v is not None: write(_filter(_v, rawExpr='${vector.id}')) # from line 45, col 17.
        write(''', sizeof(''')
        _v = VFFSL(SL,"vector.type",True) # '${vector.type}' on line 45, col 38
        if _v is not None: write(_filter(_v, rawExpr='${vector.type}')) # from line 45, col 38.
        write(''') * ''')
        _v = VFFSL(SL,"vector.allocSize",True) # '${vector.allocSize}' on line 45, col 56
        if _v is not None: write(_filter(_v, rawExpr='${vector.allocSize}')) # from line 45, col 56.
        write(''');
''')
        if VFN(VFFSL(SL,"initialisationCodeBlock.codeString",True),"isspace",False)(): # generated from line 46, col 3
            write('''  // There is no stage 2
''')
        else: # generated from line 48, col 3
            vectorOverrides = []
            if VFFSL(SL,"vector.integratingComponents",True): # generated from line 50, col 5
                vectorOverrides.append(VFFSL(SL,"vector",True))
            write('''  // Stage 2 of initialisation
  ''')
            _v = VFN(VFFSL(SL,"initialisationCodeBlock",True),"loop",False)(self.insideInitialisationLoops, vectorOverrides=vectorOverrides) # '${initialisationCodeBlock.loop(self.insideInitialisationLoops, vectorOverrides=vectorOverrides), autoIndent=True}' on line 54, col 3
            if _v is not None: write(_filter(_v, autoIndent=True, rawExpr='${initialisationCodeBlock.loop(self.insideInitialisationLoops, vectorOverrides=vectorOverrides), autoIndent=True}')) # from line 54, col 3.
        write('''}

htri_t result;
hid_t hdf5_file = H5Fopen("''')
        _v = VFFSL(SL,"filename",True) # '${filename}' on line 59, col 28
        if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 59, col 28.
        write('''", H5F_ACC_RDONLY, H5P_DEFAULT);
if (hdf5_file < 0) {
  _LOG(_ERROR_LOG_LEVEL, "Unable to open input HDF5 file \'''')
        _v = VFFSL(SL,"filename",True) # '${filename}' on line 61, col 59
        if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 61, col 59.
        write('''\'. Does it exist?\\n");
}
hid_t hdf5_parent = 0;
''')
        if VFFSL(SL,"groupName",True): # generated from line 64, col 3
            write('''if ((result = H5Lexists(hdf5_file, "''')
            _v = VFFSL(SL,"groupName",True) # '${groupName}' on line 65, col 37
            if _v is not None: write(_filter(_v, rawExpr='${groupName}')) # from line 65, col 37.
            write('''", H5P_DEFAULT)) > 0) {
  hdf5_parent = H5Gopen(hdf5_file, "''')
            _v = VFFSL(SL,"groupName",True) # '${groupName}' on line 66, col 37
            if _v is not None: write(_filter(_v, rawExpr='${groupName}')) # from line 66, col 37.
            write('''");
} else if (!result) {
  _LOG(_ERROR_LOG_LEVEL, "Unable to find group \'''')
            _v = VFFSL(SL,"groupName",True) # '${groupName}' on line 68, col 49
            if _v is not None: write(_filter(_v, rawExpr='${groupName}')) # from line 68, col 49.
            write("""' in HDF5 file '""")
            _v = VFFSL(SL,"filename",True) # '${filename}' on line 68, col 77
            if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 68, col 77.
            write('''\'.\\n");
} else {
  _LOG(_ERROR_LOG_LEVEL, "Unable to determine if group \'''')
            _v = VFFSL(SL,"groupName",True) # '${groupName}' on line 70, col 57
            if _v is not None: write(_filter(_v, rawExpr='${groupName}')) # from line 70, col 57.
            write("""' exists in HDF5 file '""")
            _v = VFFSL(SL,"filename",True) # '${filename}' on line 70, col 92
            if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 70, col 92.
            write('''\'. Is the file corrupt?\\n");
}
''')
        else: # generated from line 72, col 3
            write('''if ((result = H5Lexists(hdf5_file, "/1", H5P_DEFAULT)) > 0) {
  hdf5_parent = H5Gopen(hdf5_file, "/1");
} else if (!result) {
  hdf5_parent = hdf5_file;
} else {
  _LOG(_ERROR_LOG_LEVEL, "Unable to determine if group \'/1\' exists in HDF5 file \'''')
            _v = VFFSL(SL,"filename",True) # '${filename}' on line 78, col 82
            if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 78, col 82.
            write('''\'. Is the file corrupt?\\n");
}
''')
        write('''
''')
        dimCount = len(field.dimensions)
        write('''hsize_t file_dims[''')
        _v = VFFSL(SL,"dimCount",True) # '${dimCount}' on line 83, col 19
        if _v is not None: write(_filter(_v, rawExpr='${dimCount}')) # from line 83, col 19.
        write('''];

''')
        for dimNum, dim in enumerate(field.dimensions): # generated from line 85, col 3
            dimRep = dim.inBasis(VFFSL(SL,"vector.initialBasis",True))
            write('''hid_t dataset_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 87, col 15
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 87, col 15.
            write(''';
if ((result = H5Lexists(hdf5_parent, "''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 88, col 39
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 88, col 39.
            write('''", H5P_DEFAULT))>0)
  dataset_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 89, col 11
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 89, col 11.
            write(''' = H5Dopen(hdf5_parent, "''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 89, col 50
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 89, col 50.
            write('''");
else if (!result)
  _LOG(_ERROR_LOG_LEVEL, "Error: Unable to find dimension \'''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 91, col 60
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 91, col 60.
            write('''\' in HDF5 file.\\n");
else
  _LOG(_ERROR_LOG_LEVEL, "Error: Unable to determine if dimension \'''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 93, col 68
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 93, col 68.
            write('''\' exists in HDF5 file. Is the file corrupt?\\n");
hid_t dataspace_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 94, col 17
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 94, col 17.
            write(''' = H5Dget_space(dataset_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 94, col 55
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 94, col 55.
            write(''');
file_dims[''')
            _v = VFFSL(SL,"dimNum",True) # '$dimNum' on line 95, col 11
            if _v is not None: write(_filter(_v, rawExpr='$dimNum')) # from line 95, col 11.
            write('''] = H5Sget_simple_extent_npoints(dataspace_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 95, col 61
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 95, col 61.
            write(''');
''')
            _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 96, col 1
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 96, col 1.
            write('''* ''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 96, col 17
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 96, col 17.
            write('''_inputdata = (''')
            _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 96, col 45
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 96, col 45.
            write('''*)xmds_malloc(file_dims[''')
            _v = VFFSL(SL,"dimNum",True) # '${dimNum}' on line 96, col 83
            if _v is not None: write(_filter(_v, rawExpr='${dimNum}')) # from line 96, col 83.
            write('''] * sizeof(''')
            _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 96, col 103
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 96, col 103.
            write('''));
''')
            dataType = {'real': 'H5T_NATIVE_REAL', 'long': 'H5T_NATIVE_LONG'}[VFFSL(SL,"dimRep.type",True)]
            write('''H5Dread(dataset_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 98, col 17
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 98, col 17.
            write(''', ''')
            _v = VFFSL(SL,"dataType",True) # '$dataType' on line 98, col 33
            if _v is not None: write(_filter(_v, rawExpr='$dataType')) # from line 98, col 33.
            write(''', H5S_ALL, H5S_ALL, H5P_DEFAULT, ''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 98, col 75
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 98, col 75.
            write('''_inputdata);
''')
            if isinstance(dimRep, SplitUniformDimensionRepresentation): # generated from line 99, col 5
                dimArrayName = ''.join([str(VFFSL(SL,"dimRep.name",True)),'_data'])
                _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 101, col 1
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 101, col 1.
                write('''* ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 101, col 17
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 101, col 17.
                write(''' = (''')
                _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 101, col 36
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 101, col 36.
                write('''*)xmds_malloc(''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 101, col 64
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 101, col 64.
                write(''' * sizeof(''')
                _v = VFFSL(SL,"dimRep.type",True) # '${dimRep.type}' on line 101, col 97
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.type}')) # from line 101, col 97.
                write('''));
for (long _i0 = 0; _i0 < ''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 102, col 26
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 102, col 26.
                write('''; _i0++) {
  ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 103, col 3
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 103, col 3.
                write('''[_i0] = ''')
                _v = VFFSL(SL,"dimRep.arrayName",True) # '${dimRep.arrayName}' on line 103, col 26
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.arrayName}')) # from line 103, col 26.
                write('''[(_i0 + (''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 103, col 54
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 103, col 54.
                write('''+1)/2) % ''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 103, col 86
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 103, col 86.
                write('''];
}
''')
            else: # generated from line 105, col 5
                dimArrayName = dimRep.arrayName
            if VFFSL(SL,"geometryMatchingMode",True) == 'strict' or isinstance(dimRep, NonUniformDimensionRepresentation): # generated from line 108, col 5
                write('''for (long _i0 = 0; _i0 < ''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 109, col 26
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 109, col 26.
                write('''-1; _i0++) {
  real step = ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 110, col 15
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 110, col 15.
                write('''[_i0+1] - ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 110, col 40
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 110, col 40.
                write('''[_i0];
  if (abs(''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 111, col 11
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 111, col 11.
                write('''[_i0] - ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 111, col 34
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 111, col 34.
                write('''_inputdata[_i0]) > 0.01 * step) {
    // _LOG will cause the simulation to exit
    _LOG(_ERROR_LOG_LEVEL, "Geometry matching mode is strict for dimension \'''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 113, col 77
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 113, col 77.
                write('''\'.\\n"
                           "This means that the coordinates must be the same as for the input grid.\\n"
                           "The problem was found at input_''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 115, col 60
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 115, col 60.
                write(''': %e, simulation_''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 115, col 91
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 115, col 91.
                write(''': %e, difference: %e\\n",
                           (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 116, col 34
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 116, col 34.
                write('''_inputdata[_i0], (real)''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 116, col 71
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 116, col 71.
                write('''[_i0], (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 116, col 99
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 116, col 99.
                write('''_inputdata[_i0] - ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 116, col 131
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 116, col 131.
                write('''[_i0]);
  }
}
''')
            else: # generated from line 119, col 5
                #  Here we implement any checks required for 'loose' geometryMatchingMode
                #  We know that the dimension is uniform, therefore we should first check the deltas.
                write('''// Check that the deltas are the same to within 0.1%
real ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 123, col 6
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 123, col 6.
                write('''_step = ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 123, col 28
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 123, col 28.
                write('''[1] - ''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 123, col 49
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 123, col 49.
                write('''[0];
real ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 124, col 6
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 124, col 6.
                write('''_inputdata_step = ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 124, col 38
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 124, col 38.
                write('''_inputdata[1] - ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 124, col 68
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 124, col 68.
                write('''_inputdata[0];
if (abs(''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 125, col 9
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 125, col 9.
                write('''_step - ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 125, col 31
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 125, col 31.
                write('''_inputdata_step) > 1e-3*''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 125, col 69
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 125, col 69.
                write('''_step) {
  // _LOG will cause the simulation to exit
  _LOG(_ERROR_LOG_LEVEL, "The step size in the \'''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 127, col 49
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 127, col 49.
                write('''\' dimension of the input data and simulation grid do not match.\\n"
                         "The step size in the \'''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 128, col 49
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 128, col 49.
                write('''\' dimension was %e, while the input data had step size %e.\\n",
                         (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 129, col 32
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 129, col 32.
                write('''_step, (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 129, col 59
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 129, col 59.
                write('''_inputdata_step);
}
// Check the input and simulation grids overlap
if ((''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 132, col 6
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 132, col 6.
                write('''[0] > ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 132, col 27
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 132, col 27.
                write('''_inputdata[file_dims[''')
                _v = VFFSL(SL,"dimNum",True) # '${dimNum}' on line 132, col 62
                if _v is not None: write(_filter(_v, rawExpr='${dimNum}')) # from line 132, col 62.
                write(''']-1]) || (''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 132, col 81
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 132, col 81.
                write('''[''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 132, col 97
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 132, col 97.
                write('''-1] < ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 132, col 126
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 132, col 126.
                write('''_inputdata[0])) {
  // _LOG will cause the simulation to exit
  _LOG(_ERROR_LOG_LEVEL, "The input and simulation grids do not overlap!\\n"
                         "The simulation grid runs from %e to %e, but the input grid runs from %e to %e.\\n",
                         (real)''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 136, col 32
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 136, col 32.
                write('''[0], (real)''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 136, col 58
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 136, col 58.
                write('''[''')
                _v = VFFSL(SL,"dimRep.globalLattice",True) # '${dimRep.globalLattice}' on line 136, col 74
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.globalLattice}')) # from line 136, col 74.
                write('''-1],
                         (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 137, col 32
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 137, col 32.
                write('''_inputdata[0], (real)''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 137, col 67
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 137, col 67.
                write('''_inputdata[file_dims[''')
                _v = VFFSL(SL,"dimNum",True) # '${dimNum}' on line 137, col 102
                if _v is not None: write(_filter(_v, rawExpr='${dimNum}')) # from line 137, col 102.
                write(''']-1]);
}
real ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 139, col 6
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 139, col 6.
                write('''_fileOffsetR = (''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 139, col 36
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 139, col 36.
                write('''_inputdata[0]-''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 139, col 64
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 139, col 64.
                write('''[0])/''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 139, col 84
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 139, col 84.
                write('''_step;
if (remainder(''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 140, col 15
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 140, col 15.
                write('''_inputdata[0]-''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 140, col 43
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 140, col 43.
                write('''[0], ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 140, col 63
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 140, col 63.
                write('''_step) > 0.01*''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 140, col 91
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 140, col 91.
                write('''_step) {
  _LOG(_ERROR_LOG_LEVEL, "The input and simulation grids do not overlap sufficiently!\\n"
                         "The calculated offset for the input grid from the simulation grid in the \'''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 142, col 101
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 142, col 101.
                write('''\' dimension is %f, and it should be integral!\\n",
                         (''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 143, col 27
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 143, col 27.
                write('''_inputdata[0]-''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 143, col 55
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 143, col 55.
                write('''[0])/''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 143, col 75
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 143, col 75.
                write('''_step);
}
long ''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 145, col 6
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 145, col 6.
                write('''_fileOffset = lround((''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 145, col 42
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 145, col 42.
                write('''_inputdata[0]-''')
                _v = VFFSL(SL,"dimArrayName",True) # '${dimArrayName}' on line 145, col 70
                if _v is not None: write(_filter(_v, rawExpr='${dimArrayName}')) # from line 145, col 70.
                write('''[0])/''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 145, col 90
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 145, col 90.
                write('''_step);
''')
                dimensionOffsets[dimRep.name] = ''.join([str(VFFSL(SL,"dimRep.name",True)),'_fileOffset'])
        write('''
''')
        processingDict = {'field': field, 'operation': 'read', 'basis': basis, 'dimensionOffsets': dimensionOffsets}
        variables = [{'vector': VFFSL(SL,"vector",True), 'arrayName': ''.join(['_active_',str(VFFSL(SL,"vector.id",True))]), 'components': VFFSL(SL,"vector.components",True)}]
        write('''hid_t file_dataspace;
file_dataspace = H5Screate_simple(''')
        _v = VFFSL(SL,"len",False)(field.dimensions) # '${len(field.dimensions)}' on line 153, col 35
        if _v is not None: write(_filter(_v, rawExpr='${len(field.dimensions)}')) # from line 153, col 35.
        write(''', file_dims, NULL);
''')
        for variable in variables: # generated from line 154, col 3
            if VFFSL(SL,"variable.vector.type",True) == 'real': # generated from line 155, col 5
                variable['separatedComponents'] = list(enumerate(VFFSL(SL,"variable.components",True)))
            else: # generated from line 157, col 5
                components = []
                variable['separatedComponents'] = components
                for offset, componentName in enumerate(VFFSL(SL,"variable.components",True)): # generated from line 160, col 7
                    components.extend([(2*offset, componentName + 'R'), (2*offset+1, componentName + 'I')])
            write('''bool _variablesFound = false;
''')
            for offset, componentName in VFFSL(SL,"variable.separatedComponents",True): # generated from line 165, col 5
                write('''hid_t dataset_''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 166, col 15
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 166, col 15.
                write(''' = 0;
if ((result = H5Lexists(hdf5_parent, "''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 167, col 39
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 167, col 39.
                write('''", H5P_DEFAULT))>0) {
  dataset_''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 168, col 11
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 168, col 11.
                write(''' = H5Dopen(hdf5_parent, "''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 168, col 52
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 168, col 52.
                write('''");
  _variablesFound = true;
} else if (!result)
  _LOG(_WARNING_LOG_LEVEL, "Warning: Unable to find variable name \'''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 171, col 68
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 171, col 68.
                write('''\' in HDF5 file.\\n");
else
  _LOG(_WARNING_LOG_LEVEL, "Warning: Unable to determine if variable \'''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 173, col 71
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 173, col 71.
                write('''\' exists in HDF5 file. Is the file corrupt?\\n");
''')
        write('''
if (!_variablesFound) {
  // We haven\'t found anything. There\'s a problem with the input file.
  _LOG(_ERROR_LOG_LEVEL, "Error: None of the variables were found in the HDF5 file. Please check the file.\\n");
}
''')
        processingDict['variables'] = variables
        _v = VFFSL(SL,"processData",False)(processingDict) # '${processData(processingDict)}' on line 182, col 1
        if _v is not None: write(_filter(_v, rawExpr='${processData(processingDict)}')) # from line 182, col 1.
        write('''

''')
        for variable in variables: # generated from line 185, col 3
            for offset, componentName in VFFSL(SL,"variable.separatedComponents",True): # generated from line 186, col 5
                write('''if (dataset_''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 187, col 13
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 187, col 13.
                write(''') H5Dclose(dataset_''')
                _v = VFFSL(SL,"componentName",True) # '${componentName}' on line 187, col 48
                if _v is not None: write(_filter(_v, rawExpr='${componentName}')) # from line 187, col 48.
                write(''');
''')
        write('''H5Sclose(file_dataspace);

''')
        for dim in VFFSL(SL,"vector.field.dimensions",True): # generated from line 192, col 3
            dimRep = dim.inBasis(VFFSL(SL,"vector.initialBasis",True))
            if isinstance(dimRep, SplitUniformDimensionRepresentation): # generated from line 194, col 5
                write('''xmds_free(''')
                _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 195, col 11
                if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 195, col 11.
                write('''_data);
''')
            write('''xmds_free(''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 197, col 11
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 197, col 11.
            write('''_inputdata);
H5Sclose(dataspace_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 198, col 20
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 198, col 20.
            write(''');
H5Dclose(dataset_''')
            _v = VFFSL(SL,"dimRep.name",True) # '${dimRep.name}' on line 199, col 18
            if _v is not None: write(_filter(_v, rawExpr='${dimRep.name}')) # from line 199, col 18.
            write(''');
''')
        write('''if (hdf5_parent != hdf5_file)
  H5Gclose(hdf5_parent);
H5Fclose(hdf5_file);
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def insideInitialisationLoops(self, codeString, **KWS):



        ## CHEETAH: generated from @def insideInitialisationLoops($codeString) 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
        
        # 
        write("""// Stage 2 of initialisation

// The purpose of the following define is to give a (somewhat helpful) compile-time error
// if the user has attempted to use the propagation dimension variable in the initialisation
// block of a <vector> element. If they're trying to do this, what they really want is a 
// <computed_vector> instead.
#define """)
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 215, col 9
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 215, col 9.
        write(''' Dont_use_propagation_dimension_''')
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 215, col 64
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 215, col 64.
        write('''_in_vector_element_CDATA_block___Use_a_computed_vector_instead

// ********** Initialisation code ***************
''')
        _v = VFFSL(SL,"codeString",True) # '${codeString}' on line 218, col 1
        if _v is not None: write(_filter(_v, rawExpr='${codeString}')) # from line 218, col 1.
        write('''// **********************************************
#undef ''')
        _v = VFFSL(SL,"propagationDimension",True) # '${propagationDimension}' on line 220, col 8
        if _v is not None: write(_filter(_v, rawExpr='${propagationDimension}')) # from line 220, col 8.
        write('''
''')
        # 
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def writeBody(self, **KWS):



        ## CHEETAH: main method generated for this template
        trans = KWS.get("trans")
        if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
            trans = self.transaction # is None unless self.awake() was called
        if not trans:
            trans = DummyTransaction()
            _dummyTrans = True
        else: _dummyTrans = False
        write = trans.response().write
        SL = self._CHEETAH__searchList
        _filter = self._CHEETAH__currentFilter
        
        ########################################
        ## START - generated method body
        
        write('''
''')
        # 
        # VectorInitialisationFromHDF5.tmpl
        # 
        # Created by Graham Dennis on 2009-01-29.
        # 
        # Copyright (c) 2009-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_VectorInitialisationFromHDF5 = 'writeBody'

## END CLASS DEFINITION

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


# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://cheetahtemplate.org/

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


