#!/usr/bin/python
# -*- coding: utf-8 -*-
import os,sys,time
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree,fromstring,XML,tostring
else:
    from xml.etree.ElementTree import ElementTree,fromstring,XML,tostring

from numpy import *
import time

import Manyo.Utsusemi as mm
##import vis.VisualContCommon as VCC

#######################################
#  SampleInfo
#######################################  
class SampleInfo(object):
    """
     サンプルデータクラス
    """
    #########################################
    def __init__(self, runno=None):
        """
        コンストラクタ
        @param  runno  サンプル名=ラン番号　 
        @retval 無し
        """         
        # サンプル情報
        self.a = 1.0
        self.b = 1.0
        self.c = 1.0
        self.alpha = 90.0
        self.beta = 90.0
        self.gamma = 90.0
        self.uh = 0.0
        self.uk = 0.0
        self.ul = 1.0
        self.vh = 0.0
        self.vk = 1.0
        self.vl = 0.0
        self.fai = 0.0
        self.rotSteps = []
        # ラン番号が指定されていれば
        if runno != None:
            # サンプル情報を取得
            self._RetrieveInfo(runno)

    #########################################
    def _RetrieveInfo(self, runno):
        """
        ラン番号からサンプル情報を検索し
        データに設定
        @param  runno  サンプル名=ラン番号　 
        @retval 無し
        """             
        # パラメータディレクトリを取得
        path = UtilPlot.AcqPath().GetPrmPath()
        # パラメータファイル名(Run No. + xml)
        fpath = os.path.join(path, runno + '.xml')
        # ファイルがあるか            
        if os.path.isfile(fpath):
            # ファイルを開く
            try:
                fp =open(fpath, 'r')
                pelm = EU.ReadElement(fp)
                # メソッドのノードを取得
                mth = pelm.find(DTAG_METHOD)
            except:
                return
            # メソッドタグを取得できたか
            if mth == None:
                return
            # 回転角を取得
            gonio = mth.find(DEV_INSTNAME_GONIO)
            if gonio != None:
                prms = gonio.find(DTAG_PARAMS)
                fai = prms.find(DTAG_PSI)
                # 回転角を取得できたなら
                if fai != None:
                    try:
                        self.fai = float(fai.text)
                    except:
                        pass
            # アシスタントのタグを取得
            assist = mth.find(DTAG_ASSISTANT)
            if assist == None:
                return
            # 格子情報を取得
            lattice = assist.find(DTAG_LATTICE)
            if lattice == None:
                return
            try:
                a = lattice.find(DTAG_A)
                if a != None:
                    self.a = float(a.text)
                b = lattice.find(DTAG_B)
                if b != None:
                    self.b = float(b.text)   
                c = lattice.find(DTAG_C)
                if c != None:
                    self.c = float(c.text)
                    
                alpha = lattice.find(DTAG_ALPHA)
                if alpha != None:
                    self.alpha = float(alpha.text)
                beta = lattice.find(DTAG_BETA)
                if beta != None:
                    self.beta = float(beta.text)   
                gamma = lattice.find(DTAG_GAMMA)
                if gamma != None:
                    self.gamma = float(gamma.text)    
            except:
                return
            # 平面情報を取得
            plane = assist.find(DTAG_PLANE)
            if plane == None:
                return
            try:
                uh = plane.find(DTAG_UH)
                if uh != None:
                    self.uh = float(uh.text)
                ul = plane.find(DTAG_UL)
                if ul != None:
                    self.ul = float(ul.text)
                uk = plane.find(DTAG_UK)
                if uk != None:
                    self.uk = float(uk.text)
                vh = plane.find(DTAG_VH)
                if vh != None:
                    self.vh = float(vh.text)
                vl = plane.find(DTAG_VL)
                if vl != None:
                    self.vl = float(vl.text)
                vk = plane.find(DTAG_VK)
                if vk != None:
                    self.vk = float(vk.text)
            except:
                pass                        

    #[inamura 110206]-->
    #############################################
    def SetInfoFromHeader(self, mh=None):
        """
        """
        if type(mh)!=type(Manyo.HeaderBase()):
            raise
        try:
            if mh.CheckKey("SampleLatticeConst")!=0:
                slc = mh.PutDoubleVector("SampleLatticeConst")
                self.a = slc[0]
                self.b = slc[1]
                self.c = slc[2]
            if mh.CheckKey("SampleLatticeAngle")!=0:
                sla = mh.PutDoubleVector("SampleLatticeAngle")
                self.alpha = sla[0]
                self.beta = sla[1]
                self.gamma = sla[2]
            if mh.CheckKey("SampleUvec")!=0:
                suv = mh.PutDoubleVector("SampleUvec")
                self.uh = suv[0]
                self.uk = suv[1]
                self.ul = suv[2]
            if mh.CheckKey("SampleVvec")!=0:
                svv = mh.PutDoubleVector("SampleVvec")
                self.vh = svv[0]
                self.vk = svv[1]
                self.vl = svv[2]
            if mh.CheckKey("SampleRotateAngle")!=0:
                sra = mh.PutDoubleVector("SampleRotateAngle")
                self.fai = sra[0]
            ##[inamura 160621]-->
            if mh.CheckKey("SampleRotateSteps")!=0:
                rts = mh.PutDoubleVector("SampleRotateSteps")
                self.rotSteps = []
                for i in range( rts.size() ):
                    if i%2==0:
                        if rts[i]==0.0:
                            self.rotSteps.append( ["X",float(rts[i+1]) ] )
                        elif rts[i]==1.0:
                            self.rotSteps.append( ["Y",float(rts[i+1]) ] )
                        elif rts[i]==2.0:
                            self.rotSteps.append( ["Z",float(rts[i+1]) ] )
                        else:
                            raise UserWarning, "SampleRotateSteps in Header is invalid."
                            self.rotSteps=[]
            ##<--[inamura 160621]
        except:
            pass
        
################################
#      VisCont parameter
################################
class VisContParams(object):
    """
    Treating parameter file for VisCont seriese
    ver 0.3 [Inamura 101125]
    
    """
    __version__="0.3"

    #####################################
    def __init__(self,filepath=""):
        """
        Constructor
        @param filepath (string) path/to/xmlfile
        @return None
        """
        
        self.filepath = filepath
        self.root_ele = None        
        self.smpInfo  = None
        
        self.paxis_info = None
        self.proj_axes = None
        
        self.type_dic={"x":0,"y":0,"p":0,"t":0}
        self.folding  = [0,0,0,0]
        
        self.EnableVisType=None

        self.CommentHead = "VisContParams >> "

        if self.filepath!="":
            try:
                self.SetParamFile( self.filepath )
                self.LoadVisualContParams()
            except:
                print self.CommentHead
                pass

    #####################################
    def SetParamFile(self, filepath=""):
        """
        Set file to be imported parameters.
        @param filepath (String) path to xml file.
        @return None
        """
        if filepath!="":
            self.filepath = filepath
        
        if os.path.exists(self.filepath):
            fd = file(self.filepath,'rb')
            dom = ElementTree(file=fd)
            self.root_ele = dom.getroot()
            fd.close()
        else:
            print self.CommentHead + "Cannot read file. :"+self.filepath
            raise

    #####################################
    def LoadVisualContParams(self):
        """
        Import parameters to handle VisCont.
        @params None
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            return
        
        # import the information of lattice constants from XML file
        #self.smpInfo = VCC.SampleInfo(None)
        self.smpInfo = SampleInfo(None)
        
        smpInfo_ele = self.root_ele.find("sampleInformation")
        sliceInfo_ele = self.root_ele.find("slicingInformation")

        lattice_ele = smpInfo_ele.find("latticeInfo")
        lconst_text = lattice_ele.find("latticeConst").text
        langle_text = lattice_ele.find("latticeAngle").text
        orient_ele = smpInfo_ele.find("orientation")
        Uvec_text = orient_ele.find("Uvector").text
        Vvec_text = orient_ele.find("Vvector").text
        ##[inamura 160621]-->
        rotSteps_ele = orient_ele.find("rotateSteps") 
        if rotSteps_ele!=None:
            rotSteps_text = rotSteps_ele.text
            rotSteps_list = rotSteps_text.split(",")
            for a_step in rotSteps_list:
                vals = a_step.split(":")
                if len(vals)==2:
                    if vals[0]=="x" or vals[0]=="X":
                        self.smpInfo.rotSteps.append( ["X",float(vals[1] ) ] )
                    elif vals[0]=="y" or vals[0]=="Y":
                        self.smpInfo.rotSteps.append( ["Y",float(vals[1] ) ] )
                    elif vals[0]=="z" or vals[0]=="Z":
                        self.smpInfo.rotSteps.append( ["Z",float(vals[1] ) ] )
                    else:
                        raise UserWarning, "RotateSteps info is invalid."
        ##<--[inamura 160621]

        ##[inamura 110727]-->
        phi_ele = orient_ele.find("phi")
        if phi_ele==None:
            phi_text = orient_ele.find("fai").text
            print "VisContMParam >> This param file is old version."
        else:
            phi_text = phi_ele.text
        ##<--[inamura 110727]
        LC = lconst_text.split(",")
        LA = langle_text.split(",")
        UV = Uvec_text.split(",")
        VV = Vvec_text.split(",")

        self.smpInfo.a = float(LC[0])
        self.smpInfo.b = float(LC[1])
        self.smpInfo.c = float(LC[2])
        self.smpInfo.alpha = float(LA[0])
        self.smpInfo.beta  = float(LA[1])
        self.smpInfo.gamma = float(LA[2])
        self.smpInfo.uh = float(UV[0])
        self.smpInfo.uk = float(UV[1])
        self.smpInfo.ul = float(UV[2])
        self.smpInfo.vh = float(VV[0])
        self.smpInfo.vk = float(VV[1])
        self.smpInfo.vl = float(VV[2])

        self.smpInfo.fai = float(phi_text) ##[inamura 110727]

        # import parameters for the projection
        self.proj_axes = {}
        project_ele = sliceInfo_ele.find("projectParams")
        axis_ele_list = project_ele.findall("axis")
        
        for item in axis_ele_list:
            id = item.get("id")
            vec_el = item.find("vector")
            lt = vec_el.text.split(",")
            title = item.find("title").text
            self.proj_axes[id]=[ float(lt[0]),float(lt[1]),float(lt[2]),float(lt[3]),title ]

        # import parameters for slicing using projection parameters
        plot_ele = sliceInfo_ele.find("plotParams")
        paxis_ele_list = plot_ele.findall("paxis")
        print self.CommentHead + "num of paxis elements = ",len(paxis_ele_list)
        self.paxis_info = {}
        
        for ele in paxis_ele_list:
            id_str = ele.get("id")
            #print "id=",id_str
            type_str = ele.find("type").text
            if not self.type_dic.has_key( type_str ):
                print self.CommentHead + "type is invalid at id=",id_str
                raise
            else:
                self.type_dic[ type_str ]+=1

            range_axis = []
            if type_str!="p":
                range_str = ele.find("range").text
                range_list = range_str.split(",")
                for item in range_list:
                    range_axis.append( float(item) )
                if len(range_list)==2:
                    range_axis.append( range_axis[1]-range_axis[0] )

            folding_str = ele.find("folding").text
            if (folding_str==None) or (not (folding_str in ["0","1"]) ):
                folding=0
            else:
                folding=int(folding_str)
            
            self.paxis_info[id_str] = ( type_str, range_axis, folding )

        if (self.type_dic["x"]==1) and (self.type_dic["y"]==1):
            if (self.type_dic["p"]==1) and (self.type_dic["t"]==1):
                self.EnableVisType="VisualCont"
            elif (self.type_dic["p"]==0) and (self.type_dic["t"]==2):
                self.EnableVisType="VisualCont2"

    #####################################
    def SetLatticeConst(self,LC=[],LA=[]):
        """
        Set Lattice constant
        @param LC (list of float) Lattice constants [Angstrome]
        @[aram LA (list of float) Lattice angles [degree]
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise

        smpInfo_ele = self.root_ele.find("sampleInformation")
        lattice_ele = smpInfo_ele.find("latticeInfo")
        
        if len(LC)==3:
            self.smpInfo.a = float(LC[0])
            self.smpInfo.b = float(LC[1])
            self.smpInfo.c = float(LC[2])
            lattice_ele.find("latticeConst").text = "%f, %f, %f" % (self.smpInfo.a, self.smpInfo.b, self.smpInfo.c)
        if len(LA)==3:
            self.smpInfo.alpha = float(LA[0])
            self.smpInfo.beta  = float(LA[1])
            self.smpInfo.gamma = float(LA[2])            
            lattice_ele.find("latticeAngle").text = "%f, %f, %f" % (self.smpInfo.alpha, self.smpInfo.beta, self.smpInfo.gamma)

    #####################################
    def SetOrientationVect(self,Uvec=[],Vvec=[]):
        """
        Set Sample Orientation information
        @param Uvec (list of float) U vector (parallel to ki)
        @param Vvec (list of float) V vector (perpendicular to ki)
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise

        smpInfo_ele = self.root_ele.find("sampleInformation")
        orient_ele = smpInfo_ele.find("orientation")
        
        if len(Uvec)==3:
            self.smpInfo.uh = float(Uvec[0])
            self.smpInfo.uk = float(Uvec[1])
            self.smpInfo.ul = float(Uvec[2])
            orient_ele.find("Uvector").text = "%f, %f, %f" % (self.smpInfo.uh, self.smpInfo.uk, self.smpInfo.ul)
        if len(Vvec)==3:
            self.smpInfo.vh = float(Vvec[0])
            self.smpInfo.vk = float(Vvec[1])
            self.smpInfo.vl = float(Vvec[2])        
            orient_ele.find("Vvector").text = "%f, %f, %f" % (self.smpInfo.vh, self.smpInfo.vk, self.smpInfo.vl)

    #####################################
    def SetOrientationFai(self,fai=None):
        """
        Set Sample orientation angle
        @param fai (float) angle between U vector and ki vector [degree]
        @param return
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise
        
        if fai!=None:
            self.smpInfo.fai = float(fai)
            smpInfo_ele = self.root_ele.find("sampleInformation")
            orient_ele = smpInfo_ele.find("orientation")
            orient_ele.find("phi").text = "%f" % (self.smpInfo.fai)


    #####################################
    def SetProjectionInfo(self,terget_id=-1,vect=[],title=""):
        """
        Set Projection information
        @param terget_id (int) ID for given axis
        @param vect      (list of float) vector for axis
        @param title     (string) title of axis
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise

        if not (target_id in [0,1,2,3]):
            print self.CommentHead + "ID is invalid!!!"
            raise

        if len(vect)!=3:
            print self.CommentHead + "Vector is invalid!!!"
            raise
        
        sliceInfo_ele = self.root_ele.find("slicingInformation")
        project_ele = sliceInfo_ele.find("projectParams")
        axis_ele_list = project_ele.findall("axis")
        for item in axis_ele_list:
            id = item.get("id")
            if int(id) == target_id:
                self.proj_axes[id]=[ vect[0], vect[1], vect[2], vect[3], title ]
                item.find("vector").text = "%f, %f, %f, %f" % ( vect[0],vect[1],vect[2],vect[3] )
                item.find("title").text = title

    #####################################
    def SetSliceInfo(self,target_id=-1,type="",axrange=[],folding=False):
        """
        Set Slicing parameters
        @param target_id (int) ID for axis
        @param type      (string) "x":x-axis, "y":y-axis, "p":projection axis, "t":thickness
        @param axrange   (list)
        @param folding   (bool) folding flag (True/False)
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise
        if not (target_id in [0,1,2,3]):
            print self.CommentHead + "ID is invalid!!!"
            raise

        if not (type in self.type_dic):
            print self.CommentHead + "Type is invalid!!! ( Choose x, y, p, t )"
            raise
        
        if (len(axrange)!=2) and (len(axrange)!=3):
            print self.CommentHead + "Vector is invalid!!!"
            raise

        sliceInfo_ele = self.root_ele.find("slicingInformation")
        plot_ele = sliceInfo_ele.find("plotParams")
        paxis_ele_list = plot_ele.findall("paxis")

        
        for ele in paxis_ele_list:
            if int(ele.get("id"))==target_id:
                ele.find("type").text = type
                if (len(axrange)==2) and ( (type=="p") or (type=="t") ):
                    ele.find("range").text = "%f, %f, %f" % (axrange[0],axrange[1],(axrange[1]-axrange[0]))
                elif (len(axrange)==3) and ( (type=="p") or (type=="t") ):
                    ele.find("range").text = "%f, %f, %f" % (axrange[0],axrange[1],axrange[2])
                elif (len(axrange)==3) and ( (type=="x") or (type=="y") ):
                    ele.find("range").text = "%f, %f, %f" % (axrange[0],axrange[1],axrange[2])
                else:
                    print self.CommentHead + "Type and range is not mutch."
                    raise
                if folding:
                    fol = 1
                else:
                    fol = 0
                    
                self.paxis_info[str(target_id)] = ( type, axrange, fol )

        self.type_dic={"x":0,"y":0,"p":0,"t":0}
        for ele in paxis_ele_list:
            type_str = ele.find("type").text
            self.type_dic[ type_str ] += 1

        
        self.EnableVisType=None
        if (self.type_dic["x"]==1) and (self.type_dic["y"]==1):
            if (self.type_dic["p"]==1) and (self.type_dic["t"]==1):
                self.EnableVisType="VisualCont"
            elif (self.type_dic["p"]==0) and (self.type_dic["t"]==2):
                self.EnableVisType="VisualCont2"
                
    #####################################            
    def MakeNewParams(self):
        """
        Import new format for parameter.
        @param None
        @return None
        """
        xml_st = self.GetParamFileTemplete()
        #self.root_ele = fromstring(xml_st)
        self.root_ele = XML(xml_st)
        self.LoadVisualContParams()

    ##[inamura 110205]-->
    #####################################
    def SetAllInfo(self,smpInfo_in,axisInfo=[],sliceInfo=[]):
        """
        axisInfo= [ [ax1_a, ax1_b, ax1_c, ax1_hw, ax1_title],
                    [ax2_a, ax2_b, ax2_c, ax2_hw, ax2_title],
                    [ax3_a, ax3_b, ax3_c, ax3_hw, ax3_title],
                    [ax4_a, ax4_b, ax4_c, ax4_hw, ax4_title] ]
        sliceInfo=[ [type1, ax1_min, ax1_max, ax1_step, ax1_folding ],
                    ...
                    [type4, ax4_min, ax4_max, ax4_step, ax4_folding ] ]
        @param smpInfo_in (smpInfo class)
        @param axisInfo   (list of axis info)
        @param sliceInfo  (list of slicing parameter)
        @return None
        """
        self.smpInfo = smpInfo_in
        self.root_ele = XML( self.GetParamFileTemplete() )
        smpInfo_ele = self.root_ele.find("sampleInformation")
        
        lattice_ele = smpInfo_ele.find("latticeInfo")
        lattice_ele.find("latticeConst").text ="%f, %f, %f"% (self.smpInfo.a, self.smpInfo.b, self.smpInfo.c)
        lattice_ele.find("latticeAngle").text = "%f, %f, %f" % (self.smpInfo.alpha, self.smpInfo.beta, self.smpInfo.gamma)
        
        orient_ele = smpInfo_ele.find("orientation")
        orient_ele.find("Uvector").text = "%f, %f, %f" % (self.smpInfo.uh, self.smpInfo.uk, self.smpInfo.ul)
        orient_ele.find("Vvector").text = "%f, %f, %f" % (self.smpInfo.vh, self.smpInfo.vk, self.smpInfo.vl)
        #orient_ele.find("fai").text = "%f" % (self.smpInfo.fai)
        orient_ele.find("phi").text = "%f" % (self.smpInfo.fai)
        
        self.proj_axes = {}
        
        sliceInfo_ele = self.root_ele.find("slicingInformation")
        project_ele = sliceInfo_ele.find("projectParams")
        axis_ele_list = project_ele.findall("axis")

        for (i,axis) in enumerate(axis_ele_list):
            self.proj_axes[str(i)]=[axisInfo[i][0],axisInfo[i][1],axisInfo[i][2],axisInfo[i][3]
                                    ,axisInfo[i][4]]
            axis.find("vector").text = "%f, %f, %f, %f" % ( axisInfo[i][0],axisInfo[i][1],axisInfo[i][2],axisInfo[i][3] )
            axis.find("title").text = axisInfo[i][4]
        
        
        self.paxis_info = {}
        
        plot_ele = sliceInfo_ele.find("plotParams")
        paxis_ele_list = plot_ele.findall("paxis")
        for (i,paxis) in enumerate(paxis_ele_list):
            paxis.find("type").text = sliceInfo[i][0]
            if (sliceInfo[i][0]=="t") and ( len(sliceInfo[i])==2 ):
                axrange = [sliceInfo[i][1],sliceInfo[i][2]]
                paxis.find("range").text = "%f, %f, %f" % (axrange[0],axrange[1],(axrange[1]-axrange[0]))
            elif (sliceInfo[i][0] in ["x","y","t"]):
                axrange = [sliceInfo[i][1],sliceInfo[i][2],sliceInfo[i][3]]
                paxis.find("range").text = "%f, %f, %f" % (axrange[0],axrange[1],axrange[2])
            else:
                axrange = []
                
            paxis.find("folding").text = str(sliceInfo[i][4])

            self.paxis_info[str(i)] = ( sliceInfo[i][0], axrange, int(sliceInfo[i][4]) )

        self.type_dic={"x":0,"y":0,"p":0,"t":0}
        for ele in paxis_ele_list:
            type_str = ele.find("type").text
            self.type_dic[ type_str ] += 1

        
        self.EnableVisType=None
        if (self.type_dic["x"]==1) and (self.type_dic["y"]==1):
            if (self.type_dic["p"]==1) and (self.type_dic["t"]==1):
                self.EnableVisType="VisualCont"
            elif (self.type_dic["p"]==0) and (self.type_dic["t"]==2):
                self.EnableVisType="VisualCont2"
        
    ##<--[inamura 110205]
        
    #####################################
    def ShowParams(self):
        """
        Show all parameters
        @param None
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import file."
            raise
        print "Lattice constants"
        print "a = %f" % self.smpInfo.a
        print "b = %f" % self.smpInfo.b
        print "c = %f" % self.smpInfo.c
        print "alpha = %f" % self.smpInfo.alpha
        print "beta  = %f" % self.smpInfo.beta
        print "gamma = %f" % self.smpInfo.gamma
        print "---"
        print "Sample orientation"
        print "Uvec = [ %f, %f, %f ]" % (self.smpInfo.uh,self.smpInfo.uk,self.smpInfo.ul)
        print "Vvec = [ %f, %f, %f ]" % (self.smpInfo.vh,self.smpInfo.vk,self.smpInfo.vl)
        print "phi = %f" % self.smpInfo.fai
        print "---"
        print "Projection"
        proj_keys = self.proj_axes.keys()
        proj_keys.sort()
        for pkey in proj_keys:
            [lt0,lt1,lt2,lt3,title]=self.proj_axes[pkey]
            print "ID(%s): [%f,%f,%f,%f] :%s" % (pkey,lt0,lt1,lt2,lt3,title)

        print "---"
        print "Slicing"
        SS = ""
        paxis_ids = self.paxis_info.keys()
        paxis_ids.sort()
        for id in paxis_ids:
            (type_str, range_axis, folding) = self.paxis_info[id]
            SS = "ID(%s) : Type=%s : " % (id,type_str)
            for rr in range_axis:
                SS += " %f," % rr
            SS += " Folding=%d" % folding
            print SS

    #####################################
    def ShowXML(self):
        """
        Show XML introduced from element
        @param None
        @return None
        """
        print tostring(self.root_ele)

    #####################################
    def SaveXML(self,filename=""):
        """
        Save parameter to XML file
        @param filename (string) path and name of xml file to be saved
        @return None
        """
        if self.root_ele == None:
            print self.CommentHead + "You did not import nor make parameters."
            raise

        if os.path.exists(filename):
            print self.CommentHead+filename+" is already existed."
            
        try:
            fd = open( filename,"w" )
            fd.write( '<?xml version="1.0" encoding="utf-8"?>\n' )
            fd.write( tostring(self.root_ele) )
            fd.close()
        except:
            print self.CommentHead + " failed save to file."
            raise
        
    #####################################            
    def GetParamFileTemplete(self):
        """
        Return the templete for XML file
        @param None
        @return string of XML
        """
        return """

<visualContParams version="0.2">
  <sampleInformation>
    <name>CuGeO3</name>
    <latticeInfo>
      <latticeConst>4.81, 8.47, 2.941</latticeConst>
      <latticeAngle>90.0, 90.0, 90.0</latticeAngle>
    </latticeInfo>
    <orientation>
      <Uvector>0.0, 1.0, 0.0</Uvector>
      <Vvector>0.0, 0.0, 1.0</Vvector>
      <phi>0.0</phi>
    </orientation>
  </sampleInformation>
  <slicingInformation>
    <projectParams>
      <axis id="0">
        <vector>1.0, 0.0, 0.0, 0.0</vector>
        <title>Qa</title>
      </axis>
      <axis id="1">
        <vector>0.0, 1.0, 0.0, 0.0</vector>
        <title>Qb</title>
      </axis>
      <axis id="2">
        <vector>0.0, 0.0, 1.0, 0.0</vector>
        <title>Qc</title>
      </axis>
      <axis id="3">
        <vector>0.0, 0.0, 0.0, 1.0</vector>
        <title>hw</title>
      </axis>    
    </projectParams>

    <plotParams>
      <paxis id="0">
        <type>t</type>
        <range>-5.0,5.0,0.05</range>
        <folding>0</folding>
      </paxis>
      <paxis id="1">
        <type>p</type>
        <range></range>
        <folding>0</folding>
      </paxis>
      <paxis id="2">
        <type>x</type>
        <range>-1.5,2.0,0.02</range>
        <folding>1</folding>
      </paxis>
      <paxis id="3">
        <type>y</type>
        <range>-5.0,40.0,0.5</range>
        <folding>0</folding>
      </paxis>

    </plotParams>
  </slicingInformation>
</visualContParams>
"""
      
