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

##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '3.2.6.post2'
__CHEETAH_versionTuple__ = (3, 2, 6, 'post', 2)
__CHEETAH_genTime__ = 1634954792.9574387
__CHEETAH_genTimestamp__ = 'Sat Oct 23 13:06:32 2021'
__CHEETAH_src__ = '/home/mattias/xmds-3.0.0/admin/staging/xmds-3.1.0/xpdeint/xsil2graphics2/MathematicaImport.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 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 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('''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 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
        
        #  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 33, col 3
            _v = VFFSL(SL,"format",False)(float(listOrElement),'f') # "${format(float(listOrElement),'f')}" on line 34, col 1
            if _v is not None: write(_filter(_v, rawExpr="${format(float(listOrElement),'f')}")) # from line 34, col 1.
        else: # generated from line 35, col 3
            write('''{''')
            _v = ', '.join([VFFSL(SL,"printMathematicaListOrElement",False)(element) for element in listOrElement]) # "${', '.join([$printMathematicaListOrElement(element) for element in listOrElement])}" on line 36, col 2
            if _v is not None: write(_filter(_v, rawExpr="${', '.join([$printMathematicaListOrElement(element) for element in listOrElement])}")) # from line 36, col 2.
            write('''}''')
        
        ########################################
        ## END - generated method body
        
        return _dummyTrans and trans.response().getvalue() or ""
        

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



        ## CHEETAH: generated from @def loadXSILFile($xsilFile) at line 40, 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('''SetDirectory[NotebookDirectory[]];
''')
        declaredVars = []
        for objectNum, xsilObject in enumerate(xsilFile.xsilObjects): # generated from line 44, col 2
            if xsilObject.data.format == 'ascii': # generated from line 45, col 4
                nIndepVar = len(xsilObject.independentVariables)
                for var in xsilObject.independentVariables: # generated from line 47, col 6
                    varName = var["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    write('''Clear[''')
                    _v = VFFSL(SL,"varName",True) # '$varName' on line 50, col 7
                    if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 50, col 7.
                    write(''']
''')
                    _v = VFFSL(SL,"varName",True) # '$varName' on line 51, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 51, col 1.
                    write(''' = {''')
                    _v = ', '.join([format(float(e),'f') for e in var["array"]]) # '${\', \'.join([format(float(e),\'f\') for e in var["array"]])}' on line 51, col 13
                    if _v is not None: write(_filter(_v, rawExpr='${\', \'.join([format(float(e),\'f\') for e in var["array"]])}')) # from line 51, col 13.
                    write('''};
''')
                for varD in xsilObject.dependentVariables: # generated from line 53, col 6
                    varName = varD["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    write('''Clear[''')
                    _v = VFFSL(SL,"varName",True) # '$varName' on line 56, col 7
                    if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 56, col 7.
                    write(''']
''')
                    _v = VFFSL(SL,"varName",True) # '$varName' on line 57, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 57, col 1.
                    write(''' = ''')
                    _v = VFFSL(SL,"printMathematicaListOrElement",False)(VFFSL(SL,"varD",True)["array"]) # '$printMathematicaListOrElement($varD["array"])' on line 57, col 12
                    if _v is not None: write(_filter(_v, rawExpr='$printMathematicaListOrElement($varD["array"])')) # from line 57, col 12.
                    write(''';      
''')
                #  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 60, 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('''fpDat = OpenRead["''')
                _v = VFFSL(SL,"xsilObject.data.filename",True) # '$xsilObject.data.filename' on line 65, col 19
                if _v is not None: write(_filter(_v, rawExpr='$xsilObject.data.filename')) # from line 65, col 19.
                write('''",BinaryFormat -> True];
''')
                for var in xsilObject.independentVariables: # generated from line 66, col 6
                    varName = var["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # '$(varName)' on line 69, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$(varName)')) # from line 69, col 1.
                    write('''Len = BinaryRead[fpDat, "''')
                    _v = VFFSL(SL,"uLongFormat",True) # '$uLongFormat' on line 69, col 36
                    if _v is not None: write(_filter(_v, rawExpr='$uLongFormat')) # from line 69, col 36.
                    write('''", ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # '$machineFormat' on line 69, col 65
                    if _v is not None: write(_filter(_v, rawExpr='$machineFormat')) # from line 69, col 65.
                    write('''];
''')
                    _v = VFFSL(SL,"varName",True) # '$(varName)' on line 70, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$(varName)')) # from line 70, col 1.
                    write(''' = Flatten[BinaryReadList[fpDat, {"''')
                    _v = VFFSL(SL,"outputPrecision",True) # '$outputPrecision' on line 70, col 46
                    if _v is not None: write(_filter(_v, rawExpr='$outputPrecision')) # from line 70, col 46.
                    write('''"}, ''')
                    _v = VFFSL(SL,"varName",True) # '$(varName)' on line 70, col 66
                    if _v is not None: write(_filter(_v, rawExpr='$(varName)')) # from line 70, col 66.
                    write('''Len, ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # '$machineFormat' on line 70, col 95
                    if _v is not None: write(_filter(_v, rawExpr='$machineFormat')) # from line 70, col 95.
                    write(''']];
''')
                for varD in xsilObject.dependentVariables: # generated from line 72, col 6
                    varName = varD["name"].replace('_','') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # '$(varName)' on line 75, col 1
                    if _v is not None: write(_filter(_v, rawExpr='$(varName)')) # from line 75, col 1.
                    write('''Len = BinaryRead[fpDat, "''')
                    _v = VFFSL(SL,"uLongFormat",True) # '$uLongFormat' on line 75, col 36
                    if _v is not None: write(_filter(_v, rawExpr='$uLongFormat')) # from line 75, col 36.
                    write('''", ByteOrdering->''')
                    _v = VFFSL(SL,"machineFormat",True) # '$machineFormat' on line 75, col 65
                    if _v is not None: write(_filter(_v, rawExpr='$machineFormat')) # from line 75, col 65.
                    write('''];
''')
                    if nIndepVar<=1: # generated from line 76, col 9
                        _v = VFFSL(SL,"varName",True) # '$varName' on line 77, col 1
                        if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 77, col 1.
                        write(''' = Flatten[BinaryReadList[fpDat, {"''')
                        _v = VFFSL(SL,"outputPrecision",True) # '$outputPrecision' on line 77, col 44
                        if _v is not None: write(_filter(_v, rawExpr='$outputPrecision')) # from line 77, col 44.
                        write('''"}, ''')
                        _v = VFFSL(SL,"varName",True) # '$(varName)' on line 77, col 64
                        if _v is not None: write(_filter(_v, rawExpr='$(varName)')) # from line 77, col 64.
                        write('''Len, ByteOrdering->''')
                        _v = VFFSL(SL,"machineFormat",True) # '$machineFormat' on line 77, col 93
                        if _v is not None: write(_filter(_v, rawExpr='$machineFormat')) # from line 77, col 93.
                        write(''']];
''')
                    else: # generated from line 78, col 9
                        _v = VFFSL(SL,"varName",True) # '$varName' on line 79, col 1
                        if _v is not None: write(_filter(_v, rawExpr='$varName')) # from line 79, col 1.
                        write(''' = Flatten[Table[BinaryReadList[fpDat, {"''')
                        _v = VFFSL(SL,"outputPrecision",True) # '$outputPrecision' on line 79, col 50
                        if _v is not None: write(_filter(_v, rawExpr='$outputPrecision')) # from line 79, col 50.
                        write('''"}, ''')
                        _v = VFN(VFFSL(SL,"xsilObject",True),"independentVariables",True)[-1]["name"] # '$(xsilObject.independentVariables[-1]["name"])' on line 79, col 70
                        if _v is not None: write(_filter(_v, rawExpr='$(xsilObject.independentVariables[-1]["name"])')) # from line 79, col 70.
                        _v = VFFSL(SL,"objectNum",True)+1 # '$(objectNum+1)' on line 79, col 116
                        if _v is not None: write(_filter(_v, rawExpr='$(objectNum+1)')) # from line 79, col 116.
                        write('''Len, ByteOrdering->''')
                        _v = VFFSL(SL,"machineFormat",True) # '$machineFormat' on line 79, col 149
                        if _v is not None: write(_filter(_v, rawExpr='$machineFormat')) # from line 79, col 149.
                        write(''']''')
                        for varIndex, varI in enumerate(xsilObject.independentVariables[0:-1]): # generated from line 80, col 11
                            write(''',{j''')
                            _v = VFFSL(SL,"varIndex",True)+1 # '$(varIndex+1)' on line 81, col 4
                            if _v is not None: write(_filter(_v, rawExpr='$(varIndex+1)')) # from line 81, col 4.
                            write(''',1,''')
                            _v = VFN(VFFSL(SL,"varI",True)["name"],"replace",False)('_','') # '$(varI["name"].replace(\'_\',\'\'))' on line 81, col 20
                            if _v is not None: write(_filter(_v, rawExpr='$(varI["name"].replace(\'_\',\'\'))')) # from line 81, col 20.
                            _v = VFFSL(SL,"objectNum",True)+1 # '$(objectNum+1)' on line 81, col 51
                            if _v is not None: write(_filter(_v, rawExpr='$(objectNum+1)')) # from line 81, col 51.
                            write('''Len}''')
                        write('''],{''')
                        for varIndex, varI2 in enumerate(xsilObject.independentVariables[0:-1]): # generated from line 84, col 11
                            write('''{''')
                            _v = VFFSL(SL,"varIndex",True)+1 # '$(varIndex+1)' on line 85, col 2
                            if _v is not None: write(_filter(_v, rawExpr='$(varIndex+1)')) # from line 85, col 2.
                            write('''},''')
                        write('''{''')
                        _v = VFFSL(SL,"nIndepVar",True) # '$nIndepVar' on line 87, col 2
                        if _v is not None: write(_filter(_v, rawExpr='$nIndepVar')) # from line 87, col 2.
                        write(''',''')
                        _v = VFFSL(SL,"nIndepVar",True)+1 # '$(nIndepVar+1)' on line 87, col 13
                        if _v is not None: write(_filter(_v, rawExpr='$(nIndepVar+1)')) # from line 87, col 13.
                        write('''}}];
''')
                write('''Close[fpDat];
''')
            elif xsilObject.data.format == 'hdf5': # generated from line 91, col 4
                variables = xsilObject.independentVariables[:]
                variables.extend(xsilObject.dependentVariables)
                filename = xsilObject.data.filename
                groupName = xsilObject.data.groupName
                for var in variables: # generated from line 96, col 6
                    varName = var["name"].replace('_', '') + str(objectNum + 1)
                    declaredVars.append(varName)
                    _v = VFFSL(SL,"varName",True) # '${varName}' on line 99, col 1
                    if _v is not None: write(_filter(_v, rawExpr='${varName}')) # from line 99, col 1.
                    write(''' = Import["''')
                    _v = VFFSL(SL,"filename",True) # '${filename}' on line 99, col 22
                    if _v is not None: write(_filter(_v, rawExpr='${filename}')) # from line 99, col 22.
                    write('''", {"Datasets", "''')
                    _v = VFFSL(SL,"groupName",True) # '${groupName}' on line 99, col 50
                    if _v is not None: write(_filter(_v, rawExpr='${groupName}')) # from line 99, col 50.
                    write('''/''')
                    _v = VFFSL(SL,"var.name",True) # '${var.name}' on line 99, col 63
                    if _v is not None: write(_filter(_v, rawExpr='${var.name}')) # from line 99, col 63.
                    write('''"}];
''')
            else: # generated from line 101, col 4
                raise Exception("No support for Mathematica output for XSIL format '%s'." % xsilObject.data.format)
        write('''ResetDirectory[];

declaredVariables={''')
        _v = ', '.join([''.join(['"',str(VFFSL(SL,"dV",True)),'"']) for dV in declaredVars]) # '${\', \'.join([c\'"$dV"\' for dV in declaredVars])}' on line 107, col 20
        if _v is not None: write(_filter(_v, rawExpr='${\', \'.join([c\'"$dV"\' for dV in declaredVars])}')) # from line 107, col 20.
        write('''}
''')
        
        ########################################
        ## 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
        
        write('''
''')
        # 
        # 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('''



''')
        
        ########################################
        ## 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 https://cheetahtemplate.org/

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


