from __future__ import print_function
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 as mm
import six
#import vis.VisualContCommon as VCC

################################
#      VisContQ parameter
################################
class VisContQParams(object):
    """
    Treating parameter file for VisContQ seriese
            [inamura 160619] Bugfix of treating SampleRotateSteps
    ver 0.3 [Inamura 150527] add params for rotation steps
    ver 0.2 [Inamura 130714] add params for diagonal folding
    ver 0.1 [Inamura 110702]
    
    """
    __version__="0.3"

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

        self.CommentHead = "VisContQParams >> "

        if self.filepath!="":
            try:
                self.SetParamFile( self.filepath )
                self.LoadVisualContParams()
            except:
                print(self.CommentHead+"::constructor >> False to LoadVisualContParams")
                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 = open(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)
        
        smpInfo_ele = self.root_ele.find("sampleInformation")
        sliceInfo_ele = self.root_ele.find("slicingInformation")

        samplename_text = smpInfo_ele.find("name").text
        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
        phi_ele = orient_ele.find("phi")
        ##[inamura 150527]-->
        phi_text = "0.0"
        try:
            if phi_ele==None:
                phi_text = orient_ele.find("fai").text
                print("VisContQParam >> This param file is old version.")
            else:
                phi_text = phi_ele.text
        except:
            pass
        
        rotstep_list = []
        rotstep_ele = orient_ele.find("rotateSteps")
        if rotstep_ele!=None:
            #[inamura 160619]-->
            if isinstance(rotstep_ele.text,str):
                rotstep_text = rotstep_ele.text 
                rotstep_text_list = rotstep_text.split(",")
                for a_step in rotstep_text_list:
                    steps = a_step.split(":")
                    if len(steps)!=2:
                        print("VisContQParam >> This rotation steps info is invalid.")
                        return
                    rotstep_list.append( [ steps[0], float(steps[1]) ] )
            #<--[inamura 160619]
        if (float(phi_text)!=0.0) and (len(rotstep_list)==0):
            rotstep_list.append( ["Y", float(phi_text)] )
        ##<--[inamura 150527]
            
        LC = []
        for tmp in lconst_text.split(","):
            LC.append(float(tmp))
        
        LA = []
        for tmp in langle_text.split(","):
            LA.append(float(tmp))
        
        UV = []
        for tmp in Uvec_text.split(","):
            UV.append(float(tmp))
            
        VV = []
        for tmp in Vvec_text.split(","):
            VV.append(float(tmp))

        self.Header={}

        self.Header['SampleName'] = samplename_text
        self.Header['SimpleLatticeConsts']=LC+LA
        self.Header['SampleUvec']=UV
        self.Header['SampleVvec']=VV
        #self.Header['SampleRotatePhi']=float(phi_text)
        self.Header['SampleRotateSteps']= rotstep_list         ##[inamura 150527]
        
        """
        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(fai_text)
        """
        
        # 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")
        
        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 type_str not in self.type_dic:
                print(self.CommentHead + "type is invalid at id= {}".format(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
            ##[inamura 130624]-->
            #if (folding_str==None) or (not (folding_str in ["0","1"]) ):
            #    folding=0
            #else:
            #    folding=int(folding_str)
            folding = -1.0
            if (folding_str!=None):
                folding = float( folding_str )
                if folding<0:
                    folding = -1.0
            ##<--[inamura130624]
            
            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"

        ##[inamura 130714]-->
        dfold = plot_ele.find("diagFolding")
        if dfold!=None:
            dfold_type=int( dfold.find("type").text )
            if dfold_type in [1,2]:
                self.diag_folding[0] = dfold_type
                dfold_axes_st= dfold.find("usedAxis").text
                dfold_axes = dfold_axes_st.split(",")
                ind = 1
                for fold_axis in dfold_axes:
                    if fold_axis in ["1","2","3","4"]:
                        self.diag_folding[ind]=int(fold_axis)
                        ind +=1
                    else:
                        self.diag_folding[1]=0
                        self.diag_folding[2]=0
                        break
            else:
                self.diag_folding[0] = 0
        ##<--[inamura 130714]
    #####################################
    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 'SimpleLatticeConsts' in self.Header:
            Alc = self.Header['SimpleLatticeConsts']
        else:
            Alc = [0.0,0.0,0.0,0.0,0.0,0.0]
            
        if len(LC)==3:
            Alc[0] = float(LC[0])
            Alc[1] = float(LC[1])
            Alc[2] = float(LC[2])
            lattice_ele.find("latticeConst").text = "%f, %f, %f" % (Alc[0],Alc[1],Alc[2])
        if len(LA)==3:
            Alc[3] = float(LA[0])
            Alc[4] = float(LA[1])
            Alc[5] = float(LA[2])            
            lattice_ele.find("latticeAngle").text = "%f, %f, %f" % (Alc[3],Alc[4],Alc[5])
        
        self.Header['SimpleLatticeConsts'] = Alc
        
    #####################################
    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 "SampleUvec" in self.Header:
            h_Uv = self.Header["SampleUvec"]
            h_Vv = self.Header["SampleVvec"]
        else:
            h_Uv = [0.0,0.0,0.0]
            h_Vv = [0.0,0.0,0.0]
        
        if len(Uvec)==3:
            h_Uv[0] = float(Uvec[0])
            h_Uv[1] = float(Uvec[1])
            h_Uv[2] = float(Uvec[2])
            orient_ele.find("Uvector").text = "%f, %f, %f" % (h_Uv[0],h_Uv[1],h_Uv[2])
        if len(Vvec)==3:
            h_Vv[0] = float(Vvec[0])
            h_Vv[1] = float(Vvec[1])
            h_Vv[2] = float(Vvec[2])        
            orient_ele.find("Vvector").text = "%f, %f, %f" % (h_Vv[0], h_Vv[1], h_Vv[2])
        
        self.Header["SampleUvec"] = h_Uv
        self.Header["SampleVvec"] = h_Vv

    #####################################
    def SetOrientationPhi(self,phi=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 phi!=None:
            self.Header['SampleRotatePhi'] = float(phi)
            smpInfo_ele = self.root_ele.find("sampleInformation")
            orient_ele = smpInfo_ele.find("orientation")
            orient_ele.find("phi").text = "%f" % (self.Header['SampleRotatePhi'])
            rotateSteps_ele = orient_ele.find("rotateSteps")
            SRS_cont=[] #[inamura 160619]
            if rotateSteps_ele!=None:
                #[inamura 160619]-->
                if 'SampleRotateSteps' in self.Header:
                    RL = self.Header['SampleRotateSteps']
                    tmp_text=""
                    for a_RL in RL:
                        if a_RL[0]=="Y":
                            a_RL[1]=float(phi)
                        tmp_text+="%s:%f,"%(a_RL[0],a_RL[1])
                        SRS_cont.append( [a_RL[0],a_RL[1]] )
                    rotateSteps_ele.text = tmp_text[:-1]
                else:
                    SRS_cont = [ ["Y",float(phi)] ]
                
            self.Header['SampleRotateSteps'] = SRS_cont[:]
            #<--[inamura 160619]
            
    #####################################
    def SetOrientationRotationSteps(self,steps=[]):
        """
        Set steps of Sample orientation axis and its angle
        [inamura 150527]
        @param steps (list)  [degree]
        @param return
        """
        if self.root_ele == None:
            print(self.CommentHead + "You did not import file.")
            raise
        
        if len(steps)!=0:
            steps_text = ""
            for i in range( steps ):
                ang_info = steps[i]
                steps_text += "%s:%f,"%(steps[i][0],steps[i][1])
            steps_text = steps_text[:-1]
            
            smpInfo_ele = self.root_ele.find("sampleInformation")
            orient_ele = smpInfo_ele.find("orientation")
            orient_ele.find("rotateSteps").text = steps_text

    #####################################
    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=-1.0):
        """
        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   (float) folding flag 
        @return None
        """
        if self.root_ele == None:
            msg = self.CommentHead + "You did not import file."
            print(msg)
            raise UserWarning(msg)
        if not (target_id in [0,1,2,3]):
            msg = self.CommentHead + "ID is invalid!!!"
            print(msg)
            raise UserWarning(msg)

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

        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
                ##[inamura 130624]-->
                #if folding:
                #    fol = 1
                #else:
                #    fol = 0
                if folding<0:
                    fol = -1.0
                else:
                    fol = folding
                ##<--[inamura 130624]
                    
                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 SetDiagFoldingInfo(self,fold_type,axes=[]):
        """
        Set Diagonal Folding setting info.
        @param fold_type (int) 0:not use, 1:first-third quadrant, 2:second-forth quadrant
        @param axes ( list of int ) 2 axes for diagonal folding
        """
        if not fold_type in [0,1,2]:
            msg = self.CommentHead + "1st argument is invalid!!! (fold_type=" + str(fold_type) + ")"
            print(msg)
            raise UserWarning(msg)
        
        if len(axes)!=2:
            msg = self.CommentHead + "2nd argument is invalid!!! (ftype=" + str(fold_type) + ")"
            print(msg)
            raise UserWarning(msg)
        
        if (axes[0] in [1,2,3,4]) and (axes[1] in [1,2,3,4]):
            self.diag_folding[0] = fold_type
            self.diag_folding[1] = axes[0]
            self.diag_folding[2] = axes[1]
        else:
            self.diag_folding[0] = 0
            self.diag_folding[1] = 0
            self.diag_folding[2] = 0
        
        sliceInfo_ele = self.root_ele.find("slicingInformation")
        plot_ele = sliceInfo_ele.find("plotParams")
        if plot_ele!=None:
            diag_ele = plot_ele.find("diagFolding")
            if diag_ele!=None:
                type_ele = diag_ele.find("type")
                type_ele.text = str(self.diag_folding[0])
                usedAxis_ele = diag_ele.find("usedAxis")
                usedAxis_ele.text = "%d,%d" % (self.diag_folding[1],self.diag_folding[2])
            
    #####################################            
    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,Header_in,axisInfo=[],sliceInfo=[],foldInfo=[]):
        """
        Header_in = {"SimpleLatticeConsts":[a,b,c,alpha,beta,gamma],
                     "SampleUvec":[uh,uk,ul],
                     "SampleVvec":[vh,vk,vl],
                     "SampleRotatePhi":phi }

        axisInfo= [ [ax1_a, ax1_b, ax1_c, ax1_hw, ax1_title(string)],
                    [ax2_a, ax2_b, ax2_c, ax2_hw, ax2_title(string)],
                    [ax3_a, ax3_b, ax3_c, ax3_hw, ax3_title(string)],
                    [ax4_a, ax4_b, ax4_c, ax4_hw, ax4_title(string)] ]
        sliceInfo=[ [type1, ax1_min, ax1_max, ax1_step, ax1_folding ],
                    ...
                    [type4, ax4_min, ax4_max, ax4_step, ax4_folding ] ]
        foldInfo= [ diagonal_folding_type, axis1, axis2 ]
        
        @param smpInfo_in (smpInfo class)
        @param axisInfo   (list of axis info)
        @param sliceInfo  (list of slicing parameter)
        @return None
        """
        self.Header = Header_in
        lc = self.Header["SimpleLatticeConsts"]
        uv = self.Header["SampleUvec"]
        vv = self.Header["SampleVvec"]
        
        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"% (lc[0],lc[1],lc[2])
        lattice_ele.find("latticeAngle").text = "%f, %f, %f" % (lc[3],lc[4],lc[5])
        
        orient_ele = smpInfo_ele.find("orientation")
        orient_ele.find("Uvector").text = "%f, %f, %f" % (uv[0],uv[1],uv[2])
        orient_ele.find("Vvector").text = "%f, %f, %f" % (vv[0],vv[1],vv[2])
        ##[inamura 150527]-->
        #orient_ele.find("phi").text = "%f" % (self.Header["SampleRotatePhi"])
        rotstep_list = self.Header['SampleRotateSteps']
        steps_text = ""
        for i in range( len(rotstep_list) ):
            ang_info = rotstep_list[i]
            steps_text += "%s:%f,"%(rotstep_list[i][0],rotstep_list[i][1])
        steps_text = steps_text[:-1]
        orient_ele.find("rotateSteps").text = steps_text
        ##<--[inamura 150527]
        
        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"
        
        if len(foldInfo)==3:
            self.SetDiagFoldingInfo(foldInfo[0],foldInfo[1:])
            
    ##<--[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

        lc = self.Header["SimpleLatticeConsts"]
        uv = self.Header["SampleUvec"]
        vv = self.Header["SampleVvec"]

        print("Lattice constants")
        print("a = %f" % lc[0])
        print("b = %f" % lc[1])
        print("c = %f" % lc[2])
        print("alpha = %f" % lc[3])
        print("beta  = %f" % lc[4])
        print("gamma = %f" % lc[5])
        print("---")
        print("Sample orientation")
        print("Uvec = [ %f, %f, %f ]" % (uv[0],uv[1],uv[2]))
        print("Vvec = [ %f, %f, %f ]" % (vv[0],vv[1],vv[2]))
        ##[inamura 150527]-->
        #print "phi = %f" % self.Header['SampleRotatePhi']
        rotstep_list = self.Header['SampleRotateSteps']
        for i,ang in enumerate(rotstep_list):
            print("Rotation Step %d : axis=%s, and=%f"%(i,ang[0],ang[1]))
        ##<--[inamura 150527]
        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=%f" % folding ##[inamura 130624]
            print(SS)

        print("---")
        print("Diagonal Folding")
        if self.diag_folding[0]==1:
            print("Folding along diagonal line through 1st-3rd quadrant (axes id=%d,%d)" % (self.diag_folding[1],self.diag_folding[2]))
        elif self.diag_folding[0]==2:
            print("Folding along diagonal line through 2nd-4th quadrant (axes id=%d,%d)" % (self.diag_folding[1],self.diag_folding[2]))
        else:
            print("NO SET")

    #####################################
    def ShowXML(self):
        """
        Show XML introduced from element
        @param None
        @return None
        """
        if six.PY2:
            print(tostring(self.root_ele))
        else:
            print(tostring(self.root_ele,"unicode"))

    #####################################
    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' )
            if six.PY2:
                fd.write( tostring(self.root_ele) )
            else:
                fd.write( tostring(self.root_ele,"unicode") )
            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.3">
  <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>
      <rotateSteps></rotateSteps>
    </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>-1.0</folding>
      </paxis>
      <paxis id="1">
        <type>p</type>
        <range></range>
        <folding>-1.0</folding>
      </paxis>
      <paxis id="2">
        <type>x</type>
        <range>-1.5,2.0,0.02</range>
        <folding>-1.0</folding>
      </paxis>
      <paxis id="3">
        <type>y</type>
        <range>-5.0,40.0,0.5</range>
        <folding>-1.0</folding>
      </paxis>
      <diagFolding>
        <type>0</type>
        <usedAxis>0,0</usedAxis>
      </diagFolding>
    </plotParams>
  </slicingInformation>
</visualContParams>
"""
      
