#!/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

##################################################
## 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__ = 1389652446.246509
__CHEETAH_genTimestamp__ = 'Tue Jan 14 09:34:06 2014'
__CHEETAH_src__ = '/home/mattias/xmds-2.2.0/admin/staging/xmds-2.2.0/xpdeint/xsil2graphics2/MathematicaImport.tmpl'
__CHEETAH_srcLastModified__ = 'Wed Jun  5 14:30:43 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 MathematicaImport(Template):

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


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

        super(MathematicaImport, 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: Creates text to import data from XSIL files into Mathematica. 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'''Creates text to import data from XSIL files into Mathematica.''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def printMathematicaListOrElement(self, listOrElement, **KWS):



        ## CHEETAH: generated from @def printMathematicaListOrElement(listOrElement) 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
        
        #  This is a function to turn an array into a Mathematica list.  Called recursively, and assumes the elements are floats or lists.
        if isinstance(listOrElement,float): # generated from line 31, col 3
            _v = VFFSL(SL,"format",False)(float(listOrElement),'f') # u"${format(float(listOrElement),'f')}" on line 32, col 1
            if _v is not None: write(_filter(_v, rawExpr=u"${format(float(listOrElement),'f')}")) # from line 32, col 1.
        else: # generated from line 33, col 3
            write(u'''{''')
            _v = ', '.join([VFFSL(SL,"printMathematicaListOrElement",False)(element) for element in listOrElement]) # u"${', '.join([$printMathematicaListOrElement(element) for element in listOrElement])}" on line 34, col 2
            if _v is not None: write(_filter(_v, rawExpr=u"${', '.join([$printMathematicaListOrElement(element) for element in listOrElement])}")) # from line 34, col 2.
            write(u'''}''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def loadXSILFile(self, xsilFile, **KWS):



        ## CHEETAH: generated from @def loadXSILFile($xsilFile) at line 38, 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'''SetDirectory[NotebookDirectory[]];
''')
        declaredVars = []
        for objectNum, xsilObject in enumerate(xsilFile.xsilObjects): # generated from line 42, col 2
            if xsilObject.data.format == 'ascii': # generated from line 43, col 4
                nIndepVar = len(xsilObject.independentVariables)
                for var in xsilObject.independentVariables: # generated from line 45, col 6
                    varName = var["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    write(u'''Clear[''')
                    _v = VFFSL(SL,"varName",True) # u'$varName' on line 48, col 7
                    if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 48, col 7.
                    write(u''']
''')
                    _v = VFFSL(SL,"varName",True) # u'$varName' on line 49, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 49, col 1.
                    write(u''' = {''')
                    _v = ', '.join([format(float(e),'f') for e in var["array"]]) # u'${\', \'.join([format(float(e),\'f\') for e in var["array"]])}' on line 49, col 13
                    if _v is not None: write(_filter(_v, rawExpr=u'${\', \'.join([format(float(e),\'f\') for e in var["array"]])}')) # from line 49, col 13.
                    write(u'''};
''')
                for varD in xsilObject.dependentVariables: # generated from line 51, col 6
                    varName = varD["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    write(u'''Clear[''')
                    _v = VFFSL(SL,"varName",True) # u'$varName' on line 54, col 7
                    if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 54, col 7.
                    write(u''']
''')
                    _v = VFFSL(SL,"varName",True) # u'$varName' on line 55, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 55, col 1.
                    write(u''' = ''')
                    _v = VFFSL(SL,"printMathematicaListOrElement",False)(VFFSL(SL,"varD",True)["array"]) # u'$printMathematicaListOrElement($varD["array"])' on line 55, col 12
                    if _v is not None: write(_filter(_v, rawExpr=u'$printMathematicaListOrElement($varD["array"])')) # from line 55, col 12.
                    write(u''';      
''')
                #  Binary output, so we merely link to the requisite data file and write a script to import it
            elif xsilObject.data.format == 'binary': # generated from line 58, col 4
                nIndepVar = len(xsilObject.independentVariables)
                machineFormat = {'BigEndian': '1', 'LittleEndian': '-1'}.get(xsilObject.data.encoding, '$ByteOrdering')
                uLongFormat = {'uint32': 'UnsignedInteger32', 'uint64': 'UnsignedInteger64'}.get(xsilObject.data.uLong, 'UnsignedInteger32')
                outputPrecision = {'single': 'Real32', 'double': 'Real64'}.get(xsilObject.data.precision, 'Real64')
                write(u'''fpDat = OpenRead["''')
                _v = VFFSL(SL,"xsilObject.data.filename",True) # u'$xsilObject.data.filename' on line 63, col 19
                if _v is not None: write(_filter(_v, rawExpr=u'$xsilObject.data.filename')) # from line 63, col 19.
                write(u'''",BinaryFormat -> True];
''')
                for var in xsilObject.independentVariables: # generated from line 64, col 6
                    varName = var["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # u'$(varName)' on line 67, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$(varName)')) # from line 67, col 1.
                    write(u'''Len = BinaryRead[fpDat, "''')
                    _v = VFFSL(SL,"uLongFormat",True) # u'$uLongFormat' on line 67, col 36
                    if _v is not None: write(_filter(_v, rawExpr=u'$uLongFormat')) # from line 67, col 36.
                    write(u'''", ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # u'$machineFormat' on line 67, col 65
                    if _v is not None: write(_filter(_v, rawExpr=u'$machineFormat')) # from line 67, col 65.
                    write(u'''];
''')
                    _v = VFFSL(SL,"varName",True) # u'$(varName)' on line 68, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$(varName)')) # from line 68, col 1.
                    write(u''' = Flatten[BinaryReadList[fpDat, {"''')
                    _v = VFFSL(SL,"outputPrecision",True) # u'$outputPrecision' on line 68, col 46
                    if _v is not None: write(_filter(_v, rawExpr=u'$outputPrecision')) # from line 68, col 46.
                    write(u'''"}, ''')
                    _v = VFFSL(SL,"varName",True) # u'$(varName)' on line 68, col 66
                    if _v is not None: write(_filter(_v, rawExpr=u'$(varName)')) # from line 68, col 66.
                    write(u'''Len, ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # u'$machineFormat' on line 68, col 95
                    if _v is not None: write(_filter(_v, rawExpr=u'$machineFormat')) # from line 68, col 95.
                    write(u''']];
''')
                for varD in xsilObject.dependentVariables: # generated from line 70, col 6
                    varName = varD["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # u'$(varName)' on line 73, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'$(varName)')) # from line 73, col 1.
                    write(u'''Len = BinaryRead[fpDat, "''')
                    _v = VFFSL(SL,"uLongFormat",True) # u'$uLongFormat' on line 73, col 36
                    if _v is not None: write(_filter(_v, rawExpr=u'$uLongFormat')) # from line 73, col 36.
                    write(u'''", ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # u'$machineFormat' on line 73, col 65
                    if _v is not None: write(_filter(_v, rawExpr=u'$machineFormat')) # from line 73, col 65.
                    write(u'''];
''')
                    if nIndepVar<=1: # generated from line 74, col 9
                        _v = VFFSL(SL,"varName",True) # u'$varName' on line 75, col 1
                        if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 75, col 1.
                        write(u''' = Flatten[BinaryReadList[fpDat, {"''')
                        _v = VFFSL(SL,"outputPrecision",True) # u'$outputPrecision' on line 75, col 44
                        if _v is not None: write(_filter(_v, rawExpr=u'$outputPrecision')) # from line 75, col 44.
                        write(u'''"}, ''')
                        _v = VFFSL(SL,"varName",True) # u'$(varName)' on line 75, col 64
                        if _v is not None: write(_filter(_v, rawExpr=u'$(varName)')) # from line 75, col 64.
                        write(u'''Len, ByteOrdering->''')
                        _v = VFFSL(SL,"machineFormat",True) # u'$machineFormat' on line 75, col 93
                        if _v is not None: write(_filter(_v, rawExpr=u'$machineFormat')) # from line 75, col 93.
                        write(u''']];
''')
                    else: # generated from line 76, col 9
                        _v = VFFSL(SL,"varName",True) # u'$varName' on line 77, col 1
                        if _v is not None: write(_filter(_v, rawExpr=u'$varName')) # from line 77, col 1.
                        write(u''' = Flatten[Table[BinaryReadList[fpDat, {"''')
                        _v = VFFSL(SL,"outputPrecision",True) # u'$outputPrecision' on line 77, col 50
                        if _v is not None: write(_filter(_v, rawExpr=u'$outputPrecision')) # from line 77, col 50.
                        write(u'''"}, ''')
                        _v = VFN(VFFSL(SL,"xsilObject",True),"independentVariables",True)[-1]["name"] # u'$(xsilObject.independentVariables[-1]["name"])' on line 77, col 70
                        if _v is not None: write(_filter(_v, rawExpr=u'$(xsilObject.independentVariables[-1]["name"])')) # from line 77, col 70.
                        _v = VFFSL(SL,"objectNum",True)+1 # u'$(objectNum+1)' on line 77, col 116
                        if _v is not None: write(_filter(_v, rawExpr=u'$(objectNum+1)')) # from line 77, col 116.
                        write(u'''Len, ByteOrdering->''')
                        _v = VFFSL(SL,"machineFormat",True) # u'$machineFormat' on line 77, col 149
                        if _v is not None: write(_filter(_v, rawExpr=u'$machineFormat')) # from line 77, col 149.
                        write(u''']''')
                        for varIndex, varI in enumerate(xsilObject.independentVariables[0:-1]): # generated from line 78, col 11
                            write(u''',{j''')
                            _v = VFFSL(SL,"varIndex",True)+1 # u'$(varIndex+1)' on line 79, col 4
                            if _v is not None: write(_filter(_v, rawExpr=u'$(varIndex+1)')) # from line 79, col 4.
                            write(u''',1,''')
                            _v = VFN(VFFSL(SL,"varI",True)["name"],"replace",False)('_','') # u'$(varI["name"].replace(\'_\',\'\'))' on line 79, col 20
                            if _v is not None: write(_filter(_v, rawExpr=u'$(varI["name"].replace(\'_\',\'\'))')) # from line 79, col 20.
                            _v = VFFSL(SL,"objectNum",True)+1 # u'$(objectNum+1)' on line 79, col 51
                            if _v is not None: write(_filter(_v, rawExpr=u'$(objectNum+1)')) # from line 79, col 51.
                            write(u'''Len}''')
                        write(u'''],{''')
                        for varIndex, varI2 in enumerate(xsilObject.independentVariables[0:-1]): # generated from line 82, col 11
                            write(u'''{''')
                            _v = VFFSL(SL,"varIndex",True)+1 # u'$(varIndex+1)' on line 83, col 2
                            if _v is not None: write(_filter(_v, rawExpr=u'$(varIndex+1)')) # from line 83, col 2.
                            write(u'''},''')
                        write(u'''{''')
                        _v = VFFSL(SL,"nIndepVar",True) # u'$nIndepVar' on line 85, col 2
                        if _v is not None: write(_filter(_v, rawExpr=u'$nIndepVar')) # from line 85, col 2.
                        write(u''',''')
                        _v = VFFSL(SL,"nIndepVar",True)+1 # u'$(nIndepVar+1)' on line 85, col 13
                        if _v is not None: write(_filter(_v, rawExpr=u'$(nIndepVar+1)')) # from line 85, col 13.
                        write(u'''}}];
''')
                write(u'''Close[fpDat];
''')
            elif xsilObject.data.format == 'hdf5': # generated from line 89, col 4
                variables = xsilObject.independentVariables[:]
                variables.extend(xsilObject.dependentVariables)
                filename = xsilObject.data.filename
                groupName = xsilObject.data.groupName
                for var in variables: # generated from line 94, col 6
                    varName = var["name"].replace('_', '') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # u'${varName}' on line 97, col 1
                    if _v is not None: write(_filter(_v, rawExpr=u'${varName}')) # from line 97, col 1.
                    write(u''' = Import["''')
                    _v = VFFSL(SL,"filename",True) # u'${filename}' on line 97, col 22
                    if _v is not None: write(_filter(_v, rawExpr=u'${filename}')) # from line 97, col 22.
                    write(u'''", {"Datasets", "''')
                    _v = VFFSL(SL,"groupName",True) # u'${groupName}' on line 97, col 50
                    if _v is not None: write(_filter(_v, rawExpr=u'${groupName}')) # from line 97, col 50.
                    write(u'''/''')
                    _v = VFFSL(SL,"var.name",True) # u'${var.name}' on line 97, col 63
                    if _v is not None: write(_filter(_v, rawExpr=u'${var.name}')) # from line 97, col 63.
                    write(u'''"}];
''')
            else: # generated from line 99, col 4
                raise Exception("No support for Mathematica output for XSIL format '%s'." % xsilObject.data.format)
        write(u'''ResetDirectory[];

declaredVariables={''')
        _v = ', '.join([''.join([u'"',str(VFFSL(SL,"dV",True)),u'"']) for dV in declaredVars]) # u'${\', \'.join([c\'"$dV"\' for dV in declaredVars])}' on line 105, col 20
        if _v is not None: write(_filter(_v, rawExpr=u'${\', \'.join([c\'"$dV"\' for dV in declaredVars])}')) # from line 105, col 20.
        write(u'''}
''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

    def respond(self, trans=None):



        ## CHEETAH: main method generated for this template
        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
        
        # 
        # MathematicaImport.tmpl
        # 
        # Created by Joe Hope on 2009-01-07.
        # Modified by Graham Dennis on 2009-01-29
        # 
        # Copyright (c) 2009-2012, Joe Hope and 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__

    name = 'Mathematica 6+'

    defaultExtension = 'nb'

    _mainCheetahMethod_for_MathematicaImport= 'respond'

## END CLASS DEFINITION

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


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


