# -*- coding: utf-8 -*-

import os
import sys
import wx
import wx.xrc as xrc

import time
import threading
import thread

import Manyo as mm
import Manyo.MLF as mmm
import Manyo.Utsusemi as mu

import vis.VisContMParams as VCP
import vis.M2Plot as M2P
import vis.D2Vis as D2Vis
import vis.UtilPlot as UtilPlot

################################################
#                D4MatRSlicer
#    GUI program to treat D4MatR on Manyo-lib
#          Y.Inamura
#(2017.02.15) ver14 enable to save parameters of DataReductionPanel and small bugfix
#(2016.11.29) ver13 enable to use continuous modes with event monitor method
#(2012.11.20) ver01 firat version
################################################
__version__ = 'ver14(20170215)'

############################
## Load XMl resources file
############################
__XRCRESOURCEFILE = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],'vis','D4Mat2Slicer.xrc' )
#__XRCRESOURCEFILE = 'D4Mat2Slicer.xrc'
__res = None

def get_resources():
    """ This function provides access to the XML resources in this module."""
    global __res
    if __res == None:
        __init_resources()
    return __res

def __init_resources():
    global __res
    __res = xrc.EmptyXmlResource()

    __res.Load(__XRCRESOURCEFILE)

###############################################
class DataStoreStepByStep(object):
    def __init__(self):
        self.Ei = 0.0
        self.HW_bin = 0.0
        self.HW_min = 0.0
        self.HW_max = 0.0
        self.MaskFile = "mask.txt"
        self.GonioAtZero = 0.0
        self.Script = ""

################################################
class DataStoreContRot(object):
    def __init__(self):
        self.RunNo = 0
        self.Ei = 0.0
        self.HW_bin = 0.0
        self.HW_max = 0.0
        self.MaskFile = "mask.txt"
        self.AngleStart = 0.0
        self.AngleEnd = 0.0
        self.AngleStep = 0.0
        self.TimeSliceStart = 0.0
        self.TimeSliceEnd = 0.0
        self.Script = ""

###############################################[inamura 170215]-->
class TreatXmlParams(object):
    def __init__(self,parent):
        """
        """
        self.mode = 0
        self.runNo=0
        self.ei = 0.0
        self.energyBin = 0.0
        self.energyMin = 0.0
        self.energyMax = 0.0
        self.maskFile = ""
        self.angleStart = 0.0
        self.angleEnd = 0.0
        self.angleStep = 0.0
        self.timeSlice0 = -1
        self.timeSlice1 = -1
        self.SBS_gonioAtZero = 0.0
        self.dataReductions = {"file":""}
        self.main = parent
        if self.main.IsContinuousMethod:
            self.mode = 0

            if self.main.DataStoreContRot!=None:
                self.runNo= self.main.DataStoreContRot.RunNo
                self.ei = self.main.DataStoreContRot.Ei
                self.energyBin = self.main.DataStoreContRot.HW_bin
                self.energyMin = self.main.DataStoreContRot.HW_min
                self.energyMax = self.main.DataStoreContRot.HW_max
                self.angleStart = self.main.DataStoreContRot.AngleStart
                self.maskFile = self.main.DataStoreContRot.MaskFile
                self.angleEnd = self.main.DataStoreContRot.AngleEnd
                self.angleStep = self.main.DataStoreContRot.AngleStep
                self.timeSlice0 = self.main.DataStoreContRot.TimeSliceStart
                self.timeSlice1 = self.main.DataStoreContRot.TimeSliceEnd
                self.maskFile = self.main.DataStoreContRot.MaskFile
                self.dataReductions["file"] = self.main.DataStoreContRot.Script
        else:
            self.mode = 1

            if self.main.DataStoreStepByStep!=None:
                self.ei        = self.main.DataStoreStepByStep.Ei
                self.energyBin = self.main.DataStoreStepByStep.HW_bin
                self.energyMin = self.main.DataStoreStepByStep.HW_min
                self.energyMax = self.main.DataStoreStepByStep.HW_max
                self.maskFile = self.main.DataStoreStepByStep.MaskFile
                self.SBS_gonioAtZero = self.main.DataStoreStepByStep.GonioAtZero
                self.dataReductions["file"]=self.main.DataStoreStepByStep.Script

        self.KEY_MODE = "mode"
        self.KEY_RUNNO = "runNo"
        self.KEY_EI = "ei"
        self.KEY_EBIN = "energyBin"
        self.KEY_EMIN = "energyMin"
        self.KEY_EMAX = "energyMax"
        self.KEY_MASK = "maskFile"
        self.KEY_ANGS = "angleStart"
        self.KEY_ANGE = "angleEnd"
        self.KEY_ANGT = "angleStep"
        self.KEY_TSLS = "timeSlice"
        self.KEY_DRC  = "dataReductions"
        self.KEY_DRC_F= 'file'
        self.KEY_SBS_GONIO = "SBSgonioAtZero"
        self.KEY_RUNLIST = 'runList'
        self.KEY_RUNLIST_NUM = 'runList/num'
        self.KEY_RUNLIST_RUN = 'runList/run'

    ################################
    def load(self,filename):
        cnv = mmm.BoostXmlParser()
        if cnv.Load(str(filename)):
            rPath = "/visualContParams/d4mat2slicer"
            if cnv.hasPath(rPath):
                modepath = rPath+"/"+self.KEY_MODE
                if cnv.hasPath( modepath ):
                    self.mode = int(cnv.PutContent( modepath ) )
                if self.mode==0:
                    pathtemp = rPath+"/params/%s"
                    if cnv.hasPath(pathtemp%(self.KEY_RUNNO)):
                        self.runNo= int(cnv.PutContent( pathtemp%(self.KEY_RUNNO) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EI)):
                        self.ei= float(cnv.PutContent( pathtemp%(self.KEY_EI) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EBIN)):
                        self.energyBin= float(cnv.PutContent( pathtemp%(self.KEY_EBIN) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EMIN)):
                        self.energyMin= float(cnv.PutContent( pathtemp%(self.KEY_EMIN) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EMAX)):
                        self.energyMax= float(cnv.PutContent( pathtemp%(self.KEY_EMAX) ))
                    if cnv.hasPath(pathtemp%(self.KEY_MASK)):
                        self.maskFile= str(cnv.PutContent( pathtemp%(self.KEY_MASK) ))
                    if cnv.hasPath(pathtemp%(self.KEY_ANGS)):
                        self.angleStart= float(cnv.PutContent( pathtemp%(self.KEY_ANGS) ))
                    if cnv.hasPath(pathtemp%(self.KEY_ANGE)):
                        self.angleEnd= float(cnv.PutContent( pathtemp%(self.KEY_ANGE) ))
                    if cnv.hasPath(pathtemp%(self.KEY_ANGT)):
                        self.angleStep= float(cnv.PutContent( pathtemp%(self.KEY_ANGT) ))
                    if cnv.hasPath(pathtemp%(self.KEY_TSLS)):
                        cont = cnv.PutContent( pathtemp%(self.KEY_TSLS) )
                        cont_v = cont.split(",")
                        if len(cont_v)==2:
                            self.timeSlice0 = float(cont_v[0])
                            self.timeSlice1 = float(cont_v[1])
                        else:
                            self.timeSlice0 = -1
                            self.timeSlice1 = -1
                    if cnv.hasPath(pathtemp%(self.KEY_DRC)):
                        fname= str(cnv.PutContent( pathtemp%(self.KEY_DRC),"%s"%(self.KEY_DRC_F) ))
                        if fname!="":
                            self.dataReductions[self.KEY_DRC_F]=fname

                    isOverWriteParams=True
                    if self.main.DataStoreContRot!=None:
                        msg = "Already Data Reduction parameters are given. Do you overwrite these parameters ?"
                        dlg = wx.MessageDialog(None, msg, "Warning", wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION )
                        if dlg.ShowModal() !=wx.ID_YES:
                            isOverWriteParams=False
                    else:
                        self.main.DataStoreContRot = DataStoreContRot()
                    if isOverWriteParams:
                        self.main.DataStoreContRot.RunNo = self.runNo
                        self.main.DataStoreContRot.Ei = self.ei
                        self.main.DataStoreContRot.HW_bin = self.energyBin
                        self.main.DataStoreContRot.HW_min = self.energyMin
                        self.main.DataStoreContRot.HW_max = self.energyMax
                        self.main.DataStoreContRot.MaskFile = self.maskFile
                        self.main.DataStoreContRot.AngleStart = self.angleStart
                        self.main.DataStoreContRot.AngleEnd = self.angleEnd
                        self.main.DataStoreContRot.AngleStep = self.angleStep
                        self.main.DataStoreContRot.TimeSliceStart = self.timeSlice0
                        self.main.DataStoreContRot.TimeSliceEnd = self.timeSlice1
                        self.main.DataStoreContRot.Script = self.dataReductions[self.KEY_DRC_F]

                    self.main.IsContinuousMethod = True
                    
                elif self.mode==1:
                    pathtemp = rPath+"/params/%s"
                    if cnv.hasPath(pathtemp%(self.KEY_EI)):
                        self.ei= float(cnv.PutContent( pathtemp%(self.KEY_EI) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EBIN)):
                        self.energyBin= float(cnv.PutContent( pathtemp%(self.KEY_EBIN) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EMIN)):
                        self.energyMin= float(cnv.PutContent( pathtemp%(self.KEY_EMIN) ))
                    if cnv.hasPath(pathtemp%(self.KEY_EMAX)):
                        self.energyMax= float(cnv.PutContent( pathtemp%(self.KEY_EMAX) ))
                    if cnv.hasPath(pathtemp%(self.KEY_MASK)):
                        self.maskFile= str(cnv.PutContent( pathtemp%(self.KEY_MASK) ))
                    if cnv.hasPath(pathtemp%(self.KEY_SBS_GONIO)):
                        self.SBS_gonioAtZero = float(cnv.PutContent( pathtemp%(self.KEY_SBS_GONIO) ))
                    if cnv.hasPath(pathtemp%(self.KEY_RUNLIST)):
                        path_key = self.KEY_RUNLIST+"/"+self.KEY_RUNLIST_NUM
                        if cnv.hasPath(pathtemp%(path_key)):
                            isOverWriteParams=True
                            if len(self.main.RunList)!=0:
                                msg = "Already RunList has been read. Do you overwrite run list ?"
                                dlg = wx.MessageDialog(None, msg, "Warning", wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION )
                                if dlg.ShowModal() !=wx.ID_YES:
                                    isOverWriteParams=False
                            if isOverWriteParams:
                                self.main.RunList = {} # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                                num_runs = int( cnv.PutContent( pathtemp%(path_key) ) )

                                for ind in range( num_runs ):
                                    path_key = self.KEY_RUNLIST+"/"+self.KEY_RUNLIST_RUN+",i=%d"%(ind)
                                    if cnv.hasPath(pathtemp%(path_key)):
                                        cont = cnv.PutContent( pathtemp%(path_key) )
                                        cl = cont.split(":") #cont = "%s:%s:%08.3f:%g:%d"%(gonio_key, ex_runs, ex_angle,ex_protons, ex_mk)
                                        if len(cl)==5:
                                            gonio_key = "%08.3f"%(float(cl[0]))
                                            self.main.RunList[gonio_key]=(int(cl[4]), cl[1], float(cl[2]), float(cl[3]), ind)
                    if cnv.hasPath(pathtemp%(self.KEY_DRC)):
                        fname= str(cnv.PutContent( pathtemp%(self.KEY_DRC),"%s"%(self.KEY_DRC_F) ))
                        if fname!="":
                            self.dataReductions[self.KEY_DRC_F]=fname
                    
                    isOverWriteParams=True
                    if self.main.DataStoreStepByStep!=None:
                        msg = "Already Data Reduction parameters are given. Do you overwrite these parameters ?"
                        dlg = wx.MessageDialog(None, msg, "Warning", wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION )
                        if dlg.ShowModal() !=wx.ID_YES:
                            isOverWriteParams=False
                    else:
                        self.main.DataStoreStepByStep = DataStoreStepByStep()
                    if isOverWriteParams:
                        self.main.DataStoreStepByStep.Ei = self.ei
                        self.main.DataStoreStepByStep.HW_bin = self.energyBin
                        self.main.DataStoreStepByStep.HW_min = self.energyMin
                        self.main.DataStoreStepByStep.HW_max = self.energyMax
                        self.main.DataStoreStepByStep.HW_bin = self.energyBin
                        self.main.DataStoreStepByStep.MaskFile = self.maskFile
                        self.main.DataStoreStepByStep.GonioAtZero = self.SBS_gonioAtZero
                        self.main.DataStoreStepByStep.Script = self.dataReductions[self.KEY_DRC_F]
                    
                    self.main.IsContinuousMethod = False
            else:
                print( "this file (%s) does not include D4Mat2 params"%(filename) )
                return False
        else:
            print( "cannot open xml file %s"%(filename) )
            return False
            
        del cnv
        return True

    ################################
    def add(self,filename):
        cnv = mmm.BoostXmlParser()
        if cnv.Load(str(filename)):
            rPath = "/visualContParams/d4mat2slicer"
            modepath = rPath+"/"+self.KEY_MODE
            if self.main.IsContinuousMethod:
                cnv.AddElement( modepath, "0" )
                pathtemp = rPath+"/params/%s"
                ret = cnv.AddElement( pathtemp%(self.KEY_RUNNO), "%d"%self.runNo )
                ret = cnv.AddElement( pathtemp%(self.KEY_EI), "%g"%self.ei )
                ret = cnv.AddElement( pathtemp%(self.KEY_EBIN), "%g"%self.energyBin )
                ret = cnv.AddElement( pathtemp%(self.KEY_EMIN), "%g"%self.energyMin )
                ret = cnv.AddElement( pathtemp%(self.KEY_EMAX), "%g"%self.energyMax )
                ret = cnv.AddElement( pathtemp%(self.KEY_MASK), "%s"%self.maskFile )
                ret = cnv.AddElement( pathtemp%(self.KEY_ANGS), "%g"%self.angleStart )
                ret = cnv.AddElement( pathtemp%(self.KEY_ANGE), "%g"%self.angleEnd )
                ret = cnv.AddElement( pathtemp%(self.KEY_ANGT), "%g"%self.angleStep )
                ret = cnv.AddElement( pathtemp%(self.KEY_TSLS), "%f,%f"%(self.timeSlice0,self.timeSlice1) )

                v_att = mm.MakeStringVector()
                v_val = mm.MakeStringVector()
                for a_key in self.dataReductions.keys():
                    v_att.push_back( a_key )
                    v_val.push_back( self.dataReductions[a_key] )
                ret = cnv.AddElement( pathtemp%(self.KEY_DRC), v_att, v_val )

            else:
                cnv.AddElement( modepath, "1" )
                pathtemp = rPath+"/params/%s"
                ret = cnv.AddElement( pathtemp%(self.KEY_EI), "%g"%self.ei )
                ret = cnv.AddElement( pathtemp%(self.KEY_EBIN), "%g"%self.energyBin )
                ret = cnv.AddElement( pathtemp%(self.KEY_EMIN), "%g"%self.energyMin )
                ret = cnv.AddElement( pathtemp%(self.KEY_EMAX), "%g"%self.energyMax )
                ret = cnv.AddElement( pathtemp%(self.KEY_MASK), "%s"%self.maskFile )
                ret = cnv.AddElement( pathtemp%(self.KEY_SBS_GONIO), "%g"%self.SBS_gonioAtZero )
                num_runs = len(self.main.RunList)
                path_key = self.KEY_RUNLIST+"/"+self.KEY_RUNLIST_NUM
                ret = cnv.AddElement( pathtemp%path_key, "%d"%num_runs )
                for cnt in range( len( self.main.RunList ) ):
                    found_key = ""
                    for gonio_key in self.main.RunList: # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                        ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                        if cnt==ex_ind:
                            found_key = gonio_key
                            break
                    if found_key=="":
                        continue
                    ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[found_key]
                    path_key = self.KEY_RUNLIST+"/"+self.KEY_RUNLIST_RUN+",i=%d"%cnt
                    cont = "%s:%s:%08.3f:%g:%d"%(found_key, ex_runs, ex_angle,ex_protons, ex_mk)
                    ret = cnv.AddElement( pathtemp%path_key, cont )
                    cnt += 1
                v_att = mm.MakeStringVector()
                v_val = mm.MakeStringVector()
                for a_key in self.dataReductions.keys():
                    v_att.push_back( a_key )
                    v_val.push_back( self.dataReductions[a_key] )
                ret = cnv.AddElement( pathtemp%(self.KEY_DRC), v_att, v_val )
                    
            if (ret):
                cnv.Save(str(filename))
            
        else:
            print( "cannot open xml file %s"%(filename) )
            return false
            
        del cnv
##<--[inamura 170215]
                
###############################################
class DataReductionPanel(wx.Frame):
    def __init__(self, parent,mainpanel):
        """
        """
        self.parent = parent
        self.main = mainpanel
        ## Make window and set Event handler
        self.frame = get_resources().LoadFrame(parent,"DataReductionPanel")
        
        self.frame.Bind( wx.EVT_BUTTON, self.OnReduction, id=xrc.XRCID("btDoReduction") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnLoadRunInfoFile, id=xrc.XRCID("btLoadRunInfoFile") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAddStepByStepRun, id=xrc.XRCID("btSbSAdd") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnClearRunInfo, id=xrc.XRCID("btClearRunInfo") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnReCalcAngle, id=xrc.XRCID("btReCalc") )
        self.StepByStepButton = xrc.XRCCTRL( self.frame, "btLoadRunInfoFile" )
        self.StepByStepButton2 = xrc.XRCCTRL( self.frame, "btSbSAdd" )
        self.StepByStepClear = xrc.XRCCTRL( self.frame, "btClearRunInfo" )
        self.StepByStepCalc = xrc.XRCCTRL( self.frame, "btReCalc" )
        self.frame.Bind( wx.EVT_BUTTON, self.OnLoadXtalParam, id=xrc.XRCID("btLoadXtalParam2") )##[inamura 170215]
        self.frame.Bind( wx.EVT_BUTTON, self.OnSaveXtalParam, id=xrc.XRCID("btSaveXtalParam2") )##[inamura 170215]
        self.frame.Bind( wx.EVT_BUTTON, self.OnSelectMaskFile, id=xrc.XRCID("btSelectMaskFile") )##[inamura 180531]

        
        ## Radio Button control for measurement method
        self.frame.Bind( wx.EVT_RADIOBUTTON, self.OnTurnRadioButtonForMethod, id=xrc.XRCID("rbContRotMethod") )
        self.frame.Bind( wx.EVT_RADIOBUTTON, self.OnTurnRadioButtonForMethod, id=xrc.XRCID("rbStepByStepMethod") )
        self.RadioButtonList = []
        self.RadioButtonList.append(xrc.XRCCTRL( self.frame, "rbContRotMethod" ) )
        self.RadioButtonList.append(xrc.XRCCTRL( self.frame, "rbStepByStepMethod" ) )

        ## Radio Button control for data reduction script
        self.frame.Bind( wx.EVT_RADIOBUTTON, self.OnTurnRadioButtonForDR, id=xrc.XRCID("rbUseDRDefault") )
        self.frame.Bind( wx.EVT_RADIOBUTTON, self.OnTurnRadioButtonForDR, id=xrc.XRCID("rbUseDRScript") )
        self.RadioButtonListForDR = []
        self.RadioButtonListForDR.append(xrc.XRCCTRL( self.frame, "rbUseDRDefault" ) )
        self.RadioButtonListForDR.append(xrc.XRCCTRL( self.frame, "rbUseDRScript" ) )
        self.isUseDRScript = False
        self.DRScriptSelectButton = xrc.XRCCTRL( self.frame, "btSelectDRScript")
        self.DRScriptTempButton = xrc.XRCCTRL( self.frame, "btMakeDRTemp")
        self.frame.Bind( wx.EVT_BUTTON, self.OnSelectDRScript, id=xrc.XRCID("btSelectDRScript") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnMakeDRScriptTemp, id=xrc.XRCID("btMakeDRTemp") )
        self.DRScriptPathLabel = xrc.XRCCTRL( self.frame, "lbDRScriptPath" )
        self.DRScriptPath = "Not Selected"
        
        ## Button control
        self.ButtonCtrlList = []
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btDoReduction" ) )
        
        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(True)

        ## Continuous Reduction Params bind
        self.PanelContRot = xrc.XRCCTRL( self.frame, "panelContRot" )
        self.ContRedParams = [None,None,None,None,None,None]
        self.ContRedParams[0] = xrc.XRCCTRL( self.frame, "txtRunNo" )
        self.ContRedParams[1] = xrc.XRCCTRL( self.frame, "txtStartDeg" )
        self.ContRedParams[2] = xrc.XRCCTRL( self.frame, "txtEndDeg" )
        self.ContRedParams[3] = xrc.XRCCTRL( self.frame, "txtStepDeg" )
        self.ContRedParams[4] = xrc.XRCCTRL( self.frame, "txtTimeSliceStart" )
        self.ContRedParams[5] = xrc.XRCCTRL( self.frame, "txtTimeSliceEnd" )
        
        ## Step by Step Param bind
        self.PanelStepByStep = xrc.XRCCTRL( self.frame, "panelStepByStep" )
        self.StepByStepParams = [None,None,None,None]
        self.StepByStepParams[0] = xrc.XRCCTRL( self.frame, "txtOrgAngle" )
        self.StepByStepParams[1] = xrc.XRCCTRL( self.frame, "txtSbSRunNo" )
        self.StepByStepParams[2] = xrc.XRCCTRL( self.frame, "txtSbSAngle" )
        self.StepByStepParams[3] = xrc.XRCCTRL( self.frame, "txtSbSProtons" )
        
        ## Reduction Params bind
        self.ReductionParams = [None,None,None,None,None]
        self.ReductionParams[0] = xrc.XRCCTRL( self.frame, "txtEi" )
        self.ReductionParams[1] = xrc.XRCCTRL( self.frame, "txtEnergyBin" )
        self.ReductionParams[2] = xrc.XRCCTRL( self.frame, "txtEnergyMin" )
        self.ReductionParams[3] = xrc.XRCCTRL( self.frame, "txtEnergyMax" )
        self.ReductionParams[4] = xrc.XRCCTRL( self.frame, "txMaskFilePath" )
        
        ## Run List 
        self.lstRunInfo = xrc.XRCCTRL(self.frame, "lstRunStepInfo" )
        images = wx.ImageList(20, 20, True)
        images.Add(UtilPlot.Images().GetBmp("Red"))        # 0
        images.Add(UtilPlot.Images().GetBmp("Green"))      # 1
        images.Add(UtilPlot.Images().GetBmp("Processing")) # 2
        images.Add(UtilPlot.Images().GetBmp("GreenEnd"))   # 3
        images.Add(UtilPlot.Images().GetBmp("RedEnd"))     # 4
        self.lstRunInfo.AssignImageList(images, wx.IMAGE_LIST_SMALL)
        
        self.lstRunInfo.InsertColumn(0, "Angle", wx.LIST_FORMAT_LEFT)
        self.lstRunInfo.InsertColumn(1, "RunNo", wx.LIST_FORMAT_LEFT)
        #self.lstRunInfo.SetColumnWidth(0, 120)
        #self.lstRunInfo.SetColumnWidth(1, 120)
        self.lstRunInfo.SetColumnWidth(0, 90)
        self.lstRunInfo.SetColumnWidth(1, 150)
        
        
        ## Reduction function
        self.DataConverter = self.main.DataConverter
        
        ## menu bar
        #menubar = get_resources().LoadMenuBar("MainMenuBar")
        #self.frame.SetMenuBar( menubar )
        #self.frame.Bind(wx.EVT_MENU, self.OnLoadD4MatR, id=xrc.XRCID('menu_load_D4MatR'))
        #self.frame.Bind(wx.EVT_MENU, self.OnSaveD4MatR, id=xrc.XRCID('menu_save_D4MatR'))
        #self.frame.Bind(wx.EVT_MENU, self.OnClose, id=xrc.XRCID('menu_exit'))
        
        ## Initialize        
        self.frame.Show()
        
        self.WorkFolderPath = ""
        
        self.D4MatR = self.main.D4MatR
        
        self.frame.Bind(wx.EVT_CLOSE, self.OnClose)
        
        self.ChangeStatusOfParts()
        ## Initialize parameters
        self.Initialize()
        
    ################################
    def Initialize(self):
        """
        """
        if self.main.IsContinuousMethod:
            self.RadioButtonList[0].SetValue(True)
            self.RadioButtonList[1].SetValue(False)
            self.OnTurnRadioButtonForMethod(self.main.IsContinuousMethod)
            self.PanelContRot.Enable(True)
            self.PanelStepByStep.Enable(False)
            if self.main.DataStoreContRot!=None:
                self.ReductionParams[0].SetValue("%g"%(self.main.DataStoreContRot.Ei))
                self.ReductionParams[1].SetValue("%g"%(self.main.DataStoreContRot.HW_bin))
                self.ReductionParams[2].SetValue("%g"%(self.main.DataStoreContRot.HW_min))
                self.ReductionParams[3].SetValue("%g"%(self.main.DataStoreContRot.HW_max))
                self.ReductionParams[4].SetValue("%s"%(self.main.DataStoreContRot.MaskFile))
                self.DRScriptPath = "%s"%(self.main.DataStoreContRot.Script)
                if self.DRScriptPath!="":
                    dirname_script = os.path.dirname( self.DRScriptPath )
                    basename_script= os.path.basename( self.DRScriptPath )
                    if dirname_script==os.getcwd():
                        self.DRScriptPathLabel.SetLabel( basename_script+"(Current Dir)" )
                    else:
                        self.DRScriptPathLabel.SetLabel( basename_script+"(%s)"%(dirname_script) )
                    self.OnTurnRadioButtonForDR(False)
                else:
                    self.OnTurnRadioButtonForDR(True)
                self.ContRedParams[0].SetValue("%d"%(self.main.DataStoreContRot.RunNo))
                self.ContRedParams[1].SetValue("%g"%(self.main.DataStoreContRot.AngleStart))
                self.ContRedParams[2].SetValue("%g"%(self.main.DataStoreContRot.AngleEnd))
                self.ContRedParams[3].SetValue("%g"%(self.main.DataStoreContRot.AngleStep))
                self.ContRedParams[4].SetValue("%g"%(self.main.DataStoreContRot.TimeSliceStart))
                self.ContRedParams[5].SetValue("%g"%(self.main.DataStoreContRot.TimeSliceEnd))
        else:
            self.RadioButtonList[0].SetValue(False)
            self.RadioButtonList[1].SetValue(True)
            self.OnTurnRadioButtonForMethod(self.main.IsContinuousMethod)
            self.PanelContRot.Enable(False)
            self.PanelStepByStep.Enable(True)
            if self.main.DataStoreStepByStep!=None:
                self.ReductionParams[0].SetValue("%g"%(self.main.DataStoreStepByStep.Ei))
                self.ReductionParams[1].SetValue("%g"%(self.main.DataStoreStepByStep.HW_bin))
                self.ReductionParams[2].SetValue("%g"%(self.main.DataStoreStepByStep.HW_min))
                self.ReductionParams[3].SetValue("%g"%(self.main.DataStoreStepByStep.HW_max))
                self.ReductionParams[4].SetValue("%s"%(self.main.DataStoreStepByStep.MaskFile))
                self.StepByStepParams[0].SetValue("%f"%(self.main.DataStoreStepByStep.GonioAtZero))
                self.DRScriptPath = "%s"%(self.main.DataStoreStepByStep.Script)
                if self.DRScriptPath!="":
                    if os.path.dirname( self.DRScriptPath )==os.getcwd():
                        self.DRScriptPathLabel.SetLabel( os.path.basename( self.DRScriptPath ) )
                    else:
                        self.DRScriptPathLabel.SetLabel( self.DRScriptPath )
                    self.OnTurnRadioButtonForDR(False)
                else:
                    self.OnTurnRadioButtonForDR(True)
            self.lstRunInfo.DeleteAllItems()
            for i in range( len(self.main.RunList) ):
                found_key=""
                for gonio_key in self.main.RunList: # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                    ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                    if ex_ind==i:
                        found_key=gonio_key
                        break
                if found_key=="":
                    continue
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[found_key]
                index = self.lstRunInfo.InsertStringItem(310, "%8.3f"%(float(found_key)))
                self.lstRunInfo.SetItemImage(index, ex_mk)
                self.lstRunInfo.SetStringItem(index, 1, ex_runs)
                self.main.RunList[gonio_key] = (ex_mk, ex_runs, ex_angle, ex_protons, index )

    #################################
    def OnTurnRadioButtonForMethod(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] onTurnRadioButton")
        if evt in [True,False]:
            if evt:
                bt = self.RadioButtonList[0]
            else:
                bt = self.RadioButtonList[1]
        else:
            bt = evt.GetEventObject()
        if (bt==self.RadioButtonList[0]):
            self.main.ShowMessage("[DRPanel] --- Continuous Rotation Method")
            self.main.IsContinuousMethod = True
            #self.main.OnLineModeBtn.Enable(True)

        elif (bt==self.RadioButtonList[1]):
            self.main.ShowMessage("[DRPanel] --- Step By Step Method")
            self.main.IsContinuousMethod = False
            #self.main.OnLineModeBtn.Enable(False)
        self.main.BtnDRExec.Enable(False)
        self.ChangeStatusOfParts()

    #################################
    def OnTurnRadioButtonForDR(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] onTurnRadioButtonForDR")
        if evt in [True,False]:
            if evt:
                bt = self.RadioButtonListForDR[0]
                self.RadioButtonListForDR[0].SetValue(True)
                self.RadioButtonListForDR[1].SetValue(False)
            else:
                bt = self.RadioButtonListForDR[1]
                self.RadioButtonListForDR[0].SetValue(False)
                self.RadioButtonListForDR[1].SetValue(True)
        else:
            bt = evt.GetEventObject()
        if (bt==self.RadioButtonListForDR[0]):
            self.main.ShowMessage("[DRPanel] --- Default Data Reduction")
            self.isUseDRScript = False
        elif (bt==self.RadioButtonListForDR[1]):
            self.main.ShowMessage("[DRPanel] --- Give Data Reduction Script")
            self.isUseDRScript = True
        self.ChangeStatusOfParts()

    #################################
    def ChangeStatusOfParts(self):
        """
        """
        self.DRScriptSelectButton.Enable(self.isUseDRScript)
        self.DRScriptTempButton.Enable(self.isUseDRScript)
        self.DRScriptPathLabel.Enable(self.isUseDRScript)
        if self.main.IsContinuousMethod:
            self.PanelContRot.Enable(True)
            self.PanelStepByStep.Enable(False)
        else:
            self.PanelContRot.Enable(False)
            self.PanelStepByStep.Enable(True)
            
    #################################
    def OnReduction(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] OnReduction")
        
        Ei = float( self.ReductionParams[0].GetValue() )
        dhw = float( self.ReductionParams[1].GetValue() )
        hw_min = float( self.ReductionParams[2].GetValue() )
        hw_max = float( self.ReductionParams[3].GetValue() )
        mask_file = str(self.ReductionParams[4].GetValue())
        if mu.FindParamFilePath( mask_file )=="":
            msg = "Mask File is not found."
            dlg = wx.MessageDialog(None, msg, "ERROR", wx.OK|wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
        if self.DRScriptPathLabel.IsEnabled():
            print ("---- self.DRScriptPath = ",self.DRScriptPath)
            if not self.CheckDRScript( self.DRScriptPath ):
                msg = "Failed to import Script File."
                dlg = wx.MessageDialog(None, msg, "ERROR", wx.OK|wx.ICON_EXCLAMATION)
                dlg.ShowModal()
                dlg.Destroy()
                return
            else:
                DR_script = self.DRScriptPath
        else:
            DR_script = ""

        if (self.main.IsContinuousMethod):
            runNo  = int( self.ContRedParams[0].GetValue() )
            st_deg = float( self.ContRedParams[1].GetValue() )
            ed_deg = float( self.ContRedParams[2].GetValue() )
            w_deg  = float( self.ContRedParams[3].GetValue() )
            t_start= float( self.ContRedParams[4].GetValue() )
            t_end  = float( self.ContRedParams[5].GetValue() )

            if self.main.DataStoreContRot==None:
                self.main.DataStoreContRot = DataStoreContRot()
            self.main.DataStoreContRot.RunNo = runNo
            self.main.DataStoreContRot.Ei = Ei
            self.main.DataStoreContRot.HW_bin = dhw
            self.main.DataStoreContRot.HW_min = hw_min
            self.main.DataStoreContRot.HW_max = hw_max
            self.main.DataStoreContRot.AngleStart = st_deg
            self.main.DataStoreContRot.AngleEnd = ed_deg
            self.main.DataStoreContRot.AngleStep = w_deg
            self.main.DataStoreContRot.TimeSliceStart = t_start
            self.main.DataStoreContRot.TimeSliceEnd = t_end
            self.main.DataStoreContRot.MaskFile = mask_file
            self.main.DataStoreContRot.Script = DR_script
            self.main.doneOnLineModeFirstPrmSet = False
            runNo_st = "%06d [ continuous ]"%(runNo)
            exp_info = "Ei=%g (meV) / Rot= %g:%g:%g (deg.)"%( Ei, st_deg, w_deg, ed_deg )
        else:
            min_runNo = 1000000
            max_runNo = -1
            min_ang = 360.0
            max_ang = -360.0
            for gonio_key in self.main.RunList: # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                for runNo_st in ex_runs.split(","):
                    runNo = int(runNo_st)
                    if runNo<min_runNo:
                        min_runNo = runNo
                    if runNo>max_runNo:
                        max_runNo = runNo
                if ex_angle<min_ang:
                    min_ang = ex_angle
                if ex_angle>max_ang:
                    max_ang = ex_angle
            runNo_st = "%06d-%06d [ Step By Step ]"%(min_runNo, max_runNo)
            if hw_max>=Ei or hw_min>hw_max or dhw<=0.0:
                msg = "Invalid Energy Parameter."
                dlg = wx.MessageDialog(None, msg, "ERROR", wx.OK|wx.ICON_EXCLAMATION)
                dlg.ShowModal()
                dlg.Destroy()
                return
            gonio_atZero = float( self.StepByStepParams[0].GetValue() )

            if self.main.DataStoreStepByStep==None:
                self.main.DataStoreStepByStep = DataStoreStepByStep()
            self.main.DataStoreStepByStep.Ei = Ei
            self.main.DataStoreStepByStep.HW_bin = dhw
            self.main.DataStoreStepByStep.HW_min = hw_min
            self.main.DataStoreStepByStep.HW_max = hw_max
            self.main.DataStoreStepByStep.MaskFile = mask_file
            self.main.DataStoreStepByStep.GonioAtZero = gonio_atZero
            self.main.DataStoreStepByStep.Script = DR_script

            exp_info = "Ei=%g (meV) ang= %s <-> %s"%( Ei, min_ang, max_ang )
        
        self.main.BtnDRExec.Enable(True)
        self.main.txtRunNo.SetLabel( runNo_st )
        self.main.txtExpInfo.SetLabel( exp_info )

        self.main.OnLineModeBtn.Enable(self.main.IsContinuousMethod)
        
    #################################
    def OnClearRunInfo(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] OnClearRunInfo")
        self.lstRunInfo.DeleteAllItems()
        self.main.RunList={}
        #self.RunList=[]
        
    #################################        
    def OnClose(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] OnClose")
        self.frame.Destroy()

    #################################
    def OnLoadRunInfoFile(self,evt):
        """
        """
        self.main.ShowMessage("[DRPanel] OnLoadRunInfoFile")
        
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Open RunInfo file ...', os.getcwd(), style=wx.OPEN, wildcard='RunInfo(*.txt)|*.txt')
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        filepath = str( dlg.GetPath() )
        
        fo = open( filepath, "r" )
        dam = fo.readline() ## first line is Titles
        runinfo_list = fo.readlines()
        fo.close()
        
        ## Get First angle
        gonio_atZero = float( self.StepByStepParams[0].GetValue() )

        ## Get the number of list
        nLine = self.lstRunInfo.GetItemCount()
        
        for i,a_runinfo in enumerate(runinfo_list):
            a_line_split = a_runinfo.split(" ")
            a_line_items = []
            for a_item in a_line_split:
                if a_item!="":
                    a_line_items.append( a_item )
            if len(a_line_items)==9:
                run_no_st = a_line_items[0]
                protons_st = a_line_items[5]
                gonio_st = a_line_items[8]
                current_angle = float(gonio_st) - gonio_atZero
                gonio_key = "%08.3f"%(float(gonio_st))
                protons = float(protons_st)
                if (protons<0.0):
                    protons = -1000000.0
                if not gonio_key in self.main.RunList: # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                    index = self.lstRunInfo.InsertStringItem(310, "%8.3f"%(current_angle) )
                    self.lstRunInfo.SetItemImage(index, 1)
                    self.lstRunInfo.SetStringItem(index, 1, run_no_st)
                    self.main.RunList[gonio_key] = ( 1, run_no_st, current_angle, -1.0*protons, index  )
                else:
                    ex_mk,ex_runs,ex_angle,ex_protons,ex_ind = self.main.RunList[gonio_key]
                    ex_runs += (","+run_no_st)
                    ex_protons -= protons
                    self.main.RunList[gonio_key] = ( ex_mk, ex_runs, ex_angle, ex_protons, ex_ind )
                    self.lstRunInfo.SetStringItem(ex_ind, 1, ex_runs)
            else:
                return
                
        ## Turn On Project Button on MainPanel
        for btn_ctrl in self.main.ButtonCtrlList:
            btn_ctrl.Enable(False)
        #self.main.ButtonCtrlList[0].Enable(True)

    #################################
    def OnReCalcAngle(self,evt=None):
        """
        """
        if len(self.main.RunList)==0:
            return

        gonio_atZero = float( self.StepByStepParams[0].GetValue() )
        for gonio_key in self.main.RunList:
            ex_mk,ex_runs,ex_angle,ex_protons,ex_ind = self.main.RunList[gonio_key]
            calc_angle = float(gonio_key) - gonio_atZero
            self.lstRunInfo.SetStringItem(ex_ind,0,"%8.3f"%(calc_angle))
            self.main.RunList[gonio_key] = ( ex_mk, ex_runs, calc_angle, ex_protons, ex_ind )
            
    #################################
    def OnAddStepByStepRun(self,evt=None):
        """
        """
        runNo_st = self.StepByStepParams[1].GetValue()
        gonio = float(self.StepByStepParams[2].GetValue())
        protons = float(self.StepByStepParams[3].GetValue())
        runNo = int(runNo_st)
        if runNo<=0:
            raise UserWarning, "Run Number is invalid."

        gonio_key = "%08.3f"%gonio
        gonio_atZero = float( self.StepByStepParams[0].GetValue() )
        calc_angle = float(gonio_key) - gonio_atZero
        if not gonio_key in self.main.RunList:
            index = self.lstRunInfo.InsertStringItem(310, "%8.3f"%(current_angle) )
            self.lstRunInfo.SetItemImage(index, 1)
            self.lstRunInfo.SetStringItem(index, 1, runNo_st)
            self.main.RunList[gonio_key] = ( 1, runNo_st, current_angle, -1.0*protons, index  )
        else:
            ex_mk,ex_runs,ex_angle,ex_protons,ex_ind = self.main.RunList[gonio_key]
            ex_runs += (","+runNo_st)
            ex_protons -= protons
            self.main.RunList[gonio_key] = ( ex_mk, ex_runs, ex_angle, ex_protons, ex_ind )
            self.lstRunInfo.SetStringItem(ex_ind, 1, ex_runs)

    ##################################
    def OnSelectMaskFile(self,evt=None):
        """
        """
        print("OnSelectMaskFile")
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Choose mask file...', os.getcwd(), style=wx.OPEN, wildcard='mask(*.txt,*.xml)|*.txt;*.xml')
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        filepath = str( dlg.GetPath() )

        found_filepath=mu.FindParamFilePath(filepath)
        if found_filepath=="":
            msg = "Not found %s"%(filepath)
            raise UserWarning(msg)

        bname = os.path.basename( found_filepath )
        if mu.FindParamFilePath( bname )=="":
            self.ReductionParams[4].SetValue("%s"%( found_filepath ) )
        else:
            self.ReductionParams[4].SetValue("%s"%( bname ) )

    ##################################
    def OnSelectDRScript(self,evt=None):
        """
        """
        print("OnSelectDRScript")
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Choose Data Reduction script file ...', os.getcwd(), style=wx.OPEN, wildcard='Python(*.py)|*.py')
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        filepath = str( dlg.GetPath() )
        if self.CheckDRScript( filepath ):
            bname = os.path.basename( filepath )
            dname = os.path.dirname( filepath )
            if dname==os.getcwd():
                self.DRScriptPathLabel.SetLabel( bname+"(Current Dir)" )
            else:
                self.DRScriptPathLabel.SetLabel( bname+"(%s)"%(dname) )
            self.DRScriptPath = filepath
        else:
            msg = "Failed to import Script File"
            dlg = wx.MessageDialog(None, msg, "ERROR", wx.OK|wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()

    ##################################
    def CheckDRScript(self,filepath):
        """
        """
        print("CheckDRScript")
        fname=os.path.basename( filepath )
        dname=os.path.dirname( filepath )
        modname = fname.split(".")[0]
        sys.path.insert(0, dname)
        try:
            TF = __import__( modname )
            if self.main.IsContinuousMethod:
                if TF.DataReductionContRot.func_name=="DataReductionContRot":
                    del TF
                    return True
            else:
                if TF.DataReduction.func_name=="DataReduction":
                    del TF
                    return True
            del TF
            return False
        except:
            return False
        
    ##################################
    def OnMakeDRScriptTemp(self,evt=None):
        """
        """
        print("OnMakeDRScriptTemp")
        if self.main.IsContinuousMethod:
            title = "Continuous Rotation Method"
            script = '''#!/usr/bin/python
# -*- coding: utf-8 -*-

########## Editable ############
#HistParam="tof,0,40000,100"
#DetParam="psd"
#DetRange="All"
#TimeRange="All"
#FrameInfo="None"
#MaskInfo="NoFile"
#CaseInfo="None"
#BGInfo="TimeDep:None"
#TofShift="None"
#AnaMode="0,-,-"
#Options="-"
################################

import DR
def DataReductionContRot( DAT, phi, Ei, hw_min, hw_max, hw_bin ):
    """
    DataReduction Script Template of D4MatSlicer2
    
    @param DAT        (ElementContainerMatrix)
    @param Ei         (float) Incident Energy [meV]
    @param phi        (float) Phi ( angle around Y axis )
    @param hw_min     (float) min value of Energy Transfer [meV]
    @param hw_max     (float) max value of Energy Transfer [meV]
    @param hw_bin     (float) binning of Energy Transfer [meV]
    @return ElementContainerMatrix : valiable name must be 'DAT'
    """
    ######################### Editable #########################
    
    print("##### phi, DAT.PutSize() = %g, %d"%(phi,DAT.PutSize()))
    
    ############################################################
    return DAT
'''
        else:
            title = "Step-By-Step Method"
            script = '''#!/usr/bin/python
# -*- coding: utf-8 -*-
import DR
def DataReduction( runNo, Ei, hw_min, hw_max, hw_bin, normFactor, maskFile ):
    """
    DataReduction Script Template of D4MatSlicer2
    @param runNo      (int) Run Number
    @param Ei         (float) Incident Energy [meV]
    @param hw_min     (float) min value of Energy Transfer [meV]
    @param hw_max     (float) max value of Energy Transfer [meV]
    @param hw_bin     (float) binning of Energy Transfer [meV]
    @param normFactor (float) normarization factor
    @param maskFile   (string) file name or file path to mask file
    @return ElementContainerMatrix : valiable name must be 'DAT'
    """
    ######################### Editable #########################
    
    DAT = DR.GetDataOfMonochroEi2(runNo,Ei,hw_bin,hw_min,hw_max,MaskFile=maskFile,NormFactor=normFactor)
    
    ############################################################
    return DAT
'''
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Choose Data Reduction script for %s'%(title), os.getcwd(), style=wx.SAVE, wildcard='Python(*.py)|*.py')
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        filepath = dlg.GetPath()
        fo = open( filepath, "w" )
        fo.write( script )
        fo.close()

        self.DRScriptPath = filepath
        bname = os.path.basename( filepath )
        dname = os.path.dirname( filepath )
        if dname==os.getcwd():
            self.DRScriptPathLabel.SetLabel( bname+"(Current Dir)" )
        else:
            self.DRScriptPathLabel.SetLabel( bname+"(%s)"%(dname) )
        

    ##################################
    def OnLoadXtalParam(self,evt=None):
        """
        """
        self.main.OnLoadXtalParam(evt)
        self.Initialize()
        
    ##################################
    def OnSaveXtalParam(self,evt=None):
        """
        """
        self.OnReduction(evt)
        self.main.OnSaveXtalParam(evt)
        
###############################################

####################################
class ExecProjectionContRot(object):
    def __init__(self,lock=None,isOnLine=False):
        """
        """
        
        self.lock = lock
        self.status = -1
        self.index = 0
        self.isOnLine = isOnLine
        
    def OnStart(self,DataConverter,D4MatR,DataStore,isRefresh=False):
        """
        """
        self.DataConverter = DataConverter
        self.D4MatR = D4MatR
        self.num_of_cases = self.DataConverter.PutNumOfCases()
        self.cond_list = self.DataConverter.PutListOfCounterConditions()
        self.isRefresh = isRefresh
        self.DataStore = DataStore
        self.num_of_updated = 0
        # サブスレッドスタート
        self.status = 0
        th = None
        if self.isOnLine:
            th = threading.Thread(target=self.__ExecFuncOnLine, args=(self.num_of_cases,self.cond_list,))
        else:
            th = threading.Thread(target=self.__ExecFuncOffLine, args=(self.num_of_cases,self.cond_list,))
        th.setDaemon(True)
        th.start()
        
    def __ExecFuncOffLine(self,num_of_cases, cond_list):
        """
        """

        IND = mm.MakeUInt4Vector()
        PHI = mm.MakeDoubleVector()
        for i in range(num_of_cases):
            IND.push_back(i+1)
            PHI.push_back( (cond_list[(i+1)*2] + cond_list[(i+1)*2 +1])/2.0 )
        #import ana.Reduction.DefaultInstParams as DFI
        #L2 = DFI.Def_L2*1000.0     # [mm]
        #dS = DFI.Def_dS        # [mm]
        hh = mm.HeaderBase()
        L2 = 1.0
        dS = 1.0
        if self.DataConverter.AddRunInfoToHeader(hh):
            L2 = hh.PutDouble("TypicalL2")
            dS = hh.PutDouble("TypicalDS")
        dOmega = dS/(L2*L2)
        mask_path = self.DataStore.MaskFile

        if self.DataStore.Script=="":
            ret = self.D4MatR.ImportEcmsContRot( self.DataConverter, IND, PHI, mask_path, dOmega )
        else:
            try:
                fname=os.path.basename( self.DataStore.Script )
                dname=os.path.dirname( self.DataStore.Script )
                modname = fname.split(".")[0]
                sys.path.insert(0, dname)
                self.TF = __import__(modname)
            except:
                mu.UtsusemiError(" ERROR on import your script "+self.DataStore.Script)
                self.index = num_of_cases
                return

            if not "DataReductionContRot" in dir(self.TF):
                mu.UtsusemiError(" ERROR wrong style of your script "+self.DataStore.Script)
                self.index = num_of_cases
                return

            self.D4MatR.AllocateD4MatPseudoOnLine( num_of_cases )
            self.num_of_updated = num_of_cases
            for i in range( num_of_cases ):
                ecm = mm.ElementContainerMatrix()
                self.DataConverter.SetElementContainerMatrix( ecm, IND[i] )
                ecm_after_script = self.DataReductionByScript(ecm,PHI[i],dOmega)
                
                self.D4MatR.ImportEcmContRot( ecm_after_script, IND[i], PHI[i] )

                del ecm
                del ecm_after_script
                
                self.index = i+1
        
        self.status = -1

    def __ExecFuncOnLine(self, num_of_cases, cond_list):
        """
        """
        
        cases = self.DataConverter.PutUpdatedCases()
        IND = mm.MakeUInt4Vector()
        PHI = mm.MakeDoubleVector()
        for i in range(cases.size()):
            if cases[i]!=0.0:
                IND.append( cases[i] )
                PHI.append( (cond_list[cases[i]*2] + cond_list[cases[i]*2 +1])/2.0 )
            
        #import ana.Reduction.DefaultInstParams as DFI
        #L2 = DFI.Def_L2*1000.0     # [mm]
        #dS = DFI.Def_dS        # [mm]
        hh = mm.HeaderBase()
        L2 = 1.0
        dS = 1.0
        if self.DataConverter.AddRunInfoToHeader(hh):
            L2 = hh.PutDouble("TypicalL2")
            dS = hh.PutDouble("TypicalDS")
        dOmega = dS/(L2*L2)
        mask_path = self.DataStore.MaskFile

        if self.DataStore.Script=="":
            ret = self.D4MatR.ImportEcmsContRotPseudoOnLine( self.DataConverter, IND, PHI, mask_path, dOmega, self.isRefresh )
        else:
            try:
                fname=os.path.basename( self.DataStore.Script )
                dname=os.path.dirname( self.DataStore.Script )
                modname = fname.split(".")[0]
                sys.path.insert(0, dname)
                self.TF = __import__(modname)
            except:
                mu.UtsusemiError(" ERROR on import your script "+self.DataStore.Script)
                self.index = num_of_cases
                return

            if not "DataReductionContRot" in dir(self.TF):
                mu.UtsusemiError(" ERROR wrong style of your script "+self.DataStore.Script)
                self.index = num_of_cases
                return

            self.num_of_updated = IND.size()
            for i in range( self.num_of_updated ):
                ecm = mm.ElementContainerMatrix()
                self.DataConverter.Output( ecm, IND[i] )
                ecm_after_script = self.DataReductionByScript(ecm,PHI[i],dOmega)
                
                self.D4MatR.ImportEcmContRot( ecm_after_script, IND[i], PHI[i] )

                del ecm
                del ecm_after_script
                
                self.index = i+1

        self.status = -1

    def DataReductionByScript(self,ecm,phi,dOmega):
        """
        """
        URI = mu.UtsusemiReductionInEla(ecm)
        URI.CalcPhi()

        if self.DataStore.MaskFile!="":
            MSK = mu.UtsusemiSetMask(ecm, self.DataStore.MaskFile)
            MSK.Execute()
            del MSK

        for j in range(ecm.PutTableSize()):
            if ecm(j).PutHeaderPointer().PutString("TYPE")=="PSD":
                for k in range(ecm(j).PutTableSize()):
                    ec = ecm(j,k)
                    sa = ec.PutHeaderPointer().PutDouble("PixelSolidAngle")
                    sa = sa/dOmega
                    if sa!=0.0:
                        ec.MulMySelf(1.0/sa)

        UIR.KiKfCorrect()
        del URI

        if ecm.PutHeaderPointer().CheckKey("KICKERCOUNT")==1:
            cnts = float( ecm.PutHeaderPointer().PutInt4("KICKERCOUNT") )
            if cnts!=0.0:
                ecm.MulMySelf( 1.0/ cnts )

        ret=self.TF.DataReductionContRot( ecm, phi, self.DataStore.Ei,
                                          self.DataStore.HW_min,self.DataStore.HW_max,
                                          self.DataStore.HW_bin)
        return ret

####################################
class ExecDataReductionStepByStep(object):
    def __init__(self,lock=None):
        """
        """
        
        self.lock = lock
        self.status = -1
        self.index = 0
        
    def OnStart(self,DataStoreStepByStep,D4MatR,cond_list):
        """
        """
        self.DataStoreStepByStep = DataStoreStepByStep
        self.D4MatR = D4MatR
        self.cond_list = cond_list
        # サブスレッドスタート
        self.status = 0
        th = threading.Thread(target=self.__ExecFunc, args=(self.cond_list,))
        th.setDaemon(True)
        th.start()
        
    def __ExecFunc(self, RunList):
        """
        """
        
        Ei = self.DataStoreStepByStep.Ei
        dhw = self.DataStoreStepByStep.HW_bin
        hw_min = self.DataStoreStepByStep.HW_min
        hw_max = self.DataStoreStepByStep.HW_max
        maskfile = self.DataStoreStepByStep.MaskFile
        script = self.DataStoreStepByStep.Script

        TF = None
        if script!="":
            modName = os.path.basename( script ).split(".")[0]
            dpath = os.path.dirname( script )
            sys.path.insert(0, dpath )
            TF = __import__( modName )
        import DR

        for i in range( len(RunList) ):
            found_key = ""
            for gonio_key in RunList:
                ex_mk,ex_runs,ex_angle,ex_protons,ex_ind = RunList[gonio_key]
                if i==ex_ind:
                    found_key = gonio_key
                    break
            if found_key=="":
                continue

            mk,runs,phi,NormFactor,ex_ind = RunList[found_key]
            if mk==3:
                continue
            print "##################################################### RunNo=%s"%(runs)
            if TF==None:
                ecm = DR.GetDataOfMonochroEi3(runs,Ei,dhw,"%g %g"%(hw_min,hw_max),MaskFile=maskfile,NormFactor=NormFactor)
            else:
                print "##### DR Script = %s"%(script)
                ecm = TF.DataReduction( runNo, Ei, hw_min, hw_max, dhw, NormFactor, maskfile )

            ret = self.D4MatR.ImportEcmStepByStep( ecm, phi, "%08.3f"%(phi) )
            print "ImportEcm(ecm) i,ret,phi=",i,ret,phi
            self.index = i
            del ecm
            time.sleep(0.1)
        
        self.status = -1

###############################################
class D4MatRSlicer(wx.Frame):
    __version__ = 'v140421'
    def __init__(self, parent):
        """
        """
        ## Make window and set Event handler
        self.frame = get_resources().LoadFrame(parent,"D4MatSlicerMain")
        
        ## bind button
        self.frame.Bind( wx.EVT_BUTTON, self.OnLoadXtalParam, id=xrc.XRCID("btLoadXtalParam") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnSaveXtalParam, id=xrc.XRCID("btSaveXtalParam") )

        self.frame.Bind( wx.EVT_BUTTON, self.OnOpenDataReduction, id=xrc.XRCID("btDataReduction") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFill, id=xrc.XRCID("btAutoFill"))
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFillAxes, id=xrc.XRCID("btAutoFillAx1") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFillAxes, id=xrc.XRCID("btAutoFillAx2") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFillAxes, id=xrc.XRCID("btAutoFillAx3") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAutoFillAxes, id=xrc.XRCID("btAutoFillAx4") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnSlice, id=xrc.XRCID("btSlice") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnSlice3D, id=xrc.XRCID("btSlice3D") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnMakeD4MatFile, id=xrc.XRCID("btMakeD4MatFile") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnConvSPEFiles, id=xrc.XRCID("btConvSPEFiles") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnProjClearAll, id=xrc.XRCID("btProjectionClear") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnProjForAll, id=xrc.XRCID("btProjectionAll") )
        
        ## Button control
        self.ButtonCtrlList = []
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btProjectionAll" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btProjectionClear" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFill" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx1" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx2" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx3" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btAutoFillAx4" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btMakeD4MatFile" ) )
        self.ButtonCtrlList.append( xrc.XRCCTRL( self.frame, "btConvSPEFiles" ) )
        self.SliceButtonCtrlList=[xrc.XRCCTRL( self.frame, "btSlice" ),xrc.XRCCTRL( self.frame, "btSlice3D" )]
        self.isEnbaleSlice = False
        self.SliceButtonCtrlList[0].Enable(False)
        self.SliceButtonCtrlList[1].Enable(False)

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.Enable(False)
        
        ## On-Line Mode Setting -->
        self.txtRunNo = xrc.XRCCTRL( self.frame, "txtRunNo" )
        self.txtExpInfo = xrc.XRCCTRL( self.frame, "txtExpInfo" )
        self.BtnReductionInfo = xrc.XRCCTRL( self.frame, "btDataReduction" )
        self.BtnDRExec = xrc.XRCCTRL( self.frame, "btDRExec" )
        self.BtnDRExec.Enable(False)
        self.frame.Bind( wx.EVT_TOGGLEBUTTON, self.OnClickOnLineMode, id=xrc.XRCID("tgbOnLineMode") )
        self.OnLineModeBtn = xrc.XRCCTRL( self.frame, "tgbOnLineMode" )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAUupdate, id=xrc.XRCID("btAUupdate") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnAUstart, id=xrc.XRCID("btAUstart") )
        self.frame.Bind( wx.EVT_BUTTON, self.OnDRExec, id=xrc.XRCID("btDRExec") )
        self.frame.Bind( wx.EVT_CHECKBOX, self.OnAUwithProjection, id=xrc.XRCID("ckAUwithProjection") )
        self.frame.Bind( wx.EVT_CHECKBOX, self.OnAUwithSlice, id=xrc.XRCID("ckAUwithSlice") )

        self.OnLineModeBtn.Enable(False)
        self.OnLineModeBtnCtrlList = []
        self.OnLineModeCkbCtrlList = []
        self.OnLineModeBtnCtrlList.append( xrc.XRCCTRL( self.frame, "btAUupdate" ) )
        self.OnLineModeBtnCtrlList.append( xrc.XRCCTRL( self.frame, "btAUstart" ) )
        self.OnLineModeCkbCtrlList.append( xrc.XRCCTRL( self.frame, "ckAUwithReduction" ) )
        self.OnLineModeCkbCtrlList.append( xrc.XRCCTRL( self.frame, "ckAUwithProjection" ) )
        self.OnLineModeCkbCtrlList.append( xrc.XRCCTRL( self.frame, "ckAUwithSlice" ) )
        self.OnLineModeCkbCtrlList[0].Enable(False)
        self.OnLineModeCkbCtrlList[0].SetValue(True)
        
        self.AUIntervalTimeTxt = xrc.XRCCTRL(self.frame, "txAUIntervalTime")
        self.AUIntervalUnit = xrc.XRCCTRL(self.frame, "txtAUunit")
        
        self.doneOnLineModeFirstPrmSet = False
        self.doneD4MatPrmSet = False
        self.IsOnLineMode = False
        self.IsAutoUpdateMode = False

        # sample rotation
        self.chrotax1 = xrc.XRCCTRL(self.frame, 'chRotateAxis1st')
        self.chrotax2 = xrc.XRCCTRL(self.frame, 'chRotateAxis2nd')
        self.chrotax3 = xrc.XRCCTRL(self.frame, 'chRotateAxis3rd')
        self.chrotax1.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes2, self.chrotax1) 
        self.chrotax2.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes2, self.chrotax2) 
        self.chrotax3.Bind(wx.EVT_CHOICE, self.OnChoiceRotateAxes2, self.chrotax3) 
        self.chRotationSteps = [self.chrotax1,self.chrotax2,self.chrotax3]        
        
        ## Sample Info Panel control
        ipanel = xrc.XRCCTRL( self.frame, "SampleInfoPanel" )
        self.SampleInfoCtrl = []
        for i in range(15):
            self.SampleInfoCtrl.append( xrc.XRCCTRL( ipanel, ("txt%d"%(i+1)) ) )
        
        ## Projection Info Panel control
        self.RunList = {} # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
        ppanel = xrc.XRCCTRL( self.frame, "ProjectionInfoPanel" )
        self.ProjectionCtrl = []
        for i in range(4):
            uv0=[]
            for j in range(5):
                uv0.append( xrc.XRCCTRL( ppanel, ("txt%d"%(i*5+j+1)) ) )
            self.ProjectionCtrl.append(uv0)
        
        ## Slice Panel control
        spanel = xrc.XRCCTRL( self.frame, "SlicingPanel" )
        self.SliceAxis = []
        self.SliceRange = []
        self.SliceFold = []

        self.DiagFoldType = xrc.XRCCTRL( self.frame, "cbDiagFoldType" )
        self.DiagFoldType.Bind(wx.EVT_CHOICE, self.OnChangeDiagFold, self.DiagFoldType )
        
        for i in range(4):
            self.SliceAxis.append( xrc.XRCCTRL( spanel, ( "v%dch" % (i+1) ) ) )
            self.SliceFold.append( xrc.XRCCTRL( spanel, ( "txtFold%d" % (i+1) ) ) )
            
        for i in range(12):
            self.SliceRange.append( xrc.XRCCTRL( spanel, ( "txt%d" % (i+1) ) ) )
        
        ## Axis type bind
        for i in range(4):
            self.SliceAxis[i].Bind(wx.EVT_CHOICE, self.OnChangeSliceAxis, self.SliceAxis[i])
        
        ## Reduction function
        self.DataReductionPanel = None
        self.DataConverter = None
        #self.DataStoreStepByStep = []
        self.DataStoreStepByStep = None
        self.RunListStepByStep = []
        self.DataStoreContRot = None

        self.IsReadyProjection = False ##[inamura 170215]
        
        ## Method Continuous or Step-by-Step
        self.IsContinuousMethod = True
        self.IsReadySlice = False
        
        self.lock = thread.allocate_lock()
        
        ## Initialize               
        self.frame.Show()
        
        self.WorkFolderPath = ""
        #self.CommentHead = "D4MatRSlicer >>> "
        self.M2Plot = None
        
        self.D4MatR = mu.UtsusemiD4Matrix2()
        
        #self.ExecProjection = ExecProjection(self.lock)
        self.ExecDataReductionStepByStep = ExecDataReductionStepByStep(self.lock)
        self.ExecProjectionContRot = ExecProjectionContRot(self.lock,False) # Off-line

        #self.RunList = []
        
        self.SliceViewer3d=None

    #################################
    def OnLoadXtalParam(self,evt):
        """
        """
        self.ShowMessage("OnLoadXtalParam")
        # open dialog
        dlg = wx.FileDialog(self.frame, 'Open VisCont Parameter file ...', os.getcwd(), style=wx.OPEN, wildcard='XML(*.xml)|*.xml')

        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get file path
        filepath = dlg.GetPath()
        dir = os.path.dirname(filepath)

        if not os.path.exists(filepath):
            ss = (" Cannot find XML file(%s)" % (filepath))
            self.ShowMessage(ss)
            raise "FileIOError",ss

        vcp = VCP.VisContMParams(filepath)

        ## Get Sample Info
        lc = vcp.Header["SimpleLatticeConsts"]
        uv = vcp.Header["SampleUvec"]
        vv = vcp.Header["SampleVvec"]
        rv = vcp.Header["SampleRotateSteps"]

        # Set text box on the panel from obtained parameters
        ## sample info, U-vector, V-vector and fai
        self.SampleInfoCtrl[0].SetValue( "%g" % float(lc[0]) )
        self.SampleInfoCtrl[1].SetValue( "%g" % float(lc[1]) )
        self.SampleInfoCtrl[2].SetValue( "%g" % float(lc[2]) )
        self.SampleInfoCtrl[3].SetValue( "%g" % float(lc[3]) )
        self.SampleInfoCtrl[4].SetValue( "%g" % float(lc[4]) )
        self.SampleInfoCtrl[5].SetValue( "%g" % float(lc[5]) )
        self.SampleInfoCtrl[6].SetValue( "%g" % float(uv[0]) )
        self.SampleInfoCtrl[7].SetValue( "%g" % float(uv[1]) )
        self.SampleInfoCtrl[8].SetValue( "%g" % float(uv[2]) )
        self.SampleInfoCtrl[9].SetValue( "%g" % float(vv[0]) )
        self.SampleInfoCtrl[10].SetValue( "%g" % float(vv[1]) )
        self.SampleInfoCtrl[11].SetValue( "%g" % float(vv[2]) )


        self.SampleInfoCtrl[12].Enable(False)
        self.SampleInfoCtrl[13].Enable(False)
        self.SampleInfoCtrl[14].Enable(False)
        
        self.chRotationSteps[0].Enable(True)
        self.chRotationSteps[0].SetSelection( 0 )
        self.chRotationSteps[1].Enable(False)
        self.chRotationSteps[1].SetSelection( 0 )
        self.chRotationSteps[2].Enable(False)
        self.chRotationSteps[2].SetSelection( 0 )
        
        ro_axis_dic={ "Y":1,"Z":2,"X":3 }
        for i,a_rot in enumerate(rv):
            ax_num=0
            try:
                ax_num = ro_axis_dic[ a_rot[0] ]
            except:
                pass
            self.chRotationSteps[i].Enable(True)
            self.chRotationSteps[i].SetSelection( ax_num )
            self.SampleInfoCtrl[12+i].SetValue( "%g" % float(a_rot[1]) )
            self.SampleInfoCtrl[12+i].Enable(True)
            if (i+1)<len(self.chRotationSteps):
                self.chRotationSteps[i+1].Enable(True)
                
        ## Projection infor
        for id in range(4):
            for col in range(4):
                self.ProjectionCtrl[id][col].SetValue( "%g" % (vcp.proj_axes[str(id)][col]) )
            self.ProjectionCtrl[id][4].SetValue( vcp.proj_axes[str(id)][4] )


        ## Slicing ranges and steps
        for id in range(4):
            type = vcp.paxis_info[str(id)][0]
            if type in ["x","y","p","t"]:
                range_axis = vcp.paxis_info[str(id)][1]
                self.SliceRange[3*id + 0].SetValue( "%g" % ( range_axis[0] ) )
                self.SliceRange[3*id + 1].SetValue( "%g" % ( range_axis[1] ) )
                self.SliceRange[3*id + 2].SetValue( "%g" % ( range_axis[2] ) )
            else:
                self.ShowMessage("type in xml file is invalid!!")
                raise
        ## axis type for slicing
        dic = {"x":0,"y":1,"p":2,"t":2 }
        for i in range(4):
            self.SliceAxis[i].SetSelection( dic[ vcp.paxis_info[ ("%1d"%(i)) ][0] ] )
            
        ## folding
        for i in range(4):
            self.SliceFold[i].SetValue( "%g" % (vcp.paxis_info[ ("%1d"%(i)) ][2]) )
        self.SetStepEnable()

        tt=TreatXmlParams(self)
        tt.load(filepath)
        del tt
        return

    #################################
    def SetStepEnable(self):
        """
        """
        for i in range(4):
            if self.SliceAxis[i].GetCurrentSelection()==2:   ## "T" is selected
                self.SliceRange[ i*3 +2 ].Enable(False)
            else:                                     ## "X" or "Y" is selected
                self.SliceRange[ i*3 +2 ].Enable(True)


    #################################
    def OnSaveXtalParam(self,evt):
        """
        """
        self.ShowMessage("OnSaveXtalParam")
        ## get Lattice consts and U,V vectors
        (Header,axisInfo) = self.GetParamsForProj(isVect=False)
        
        ## sliceInfo
        sliceInfo = self.GetParamsForSlice(isVect=False)
        
        # make instance
        vcp=VCP.VisContMParams()

        # set parameters
        vcp.SetAllInfo( Header, axisInfo, sliceInfo )

        # open dialog
        dlg = wx.FileDialog(self.frame, 'Save Cryatal Parameter File  ...', os.getcwd(), style=wx.SAVE, wildcard='XML(*.xml)|*.xml')

        # if cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return

        # get file path
        savefile = dlg.GetPath()
        dir = os.path.dirname(savefile)

        # show parameters to be checked
        vcp.ShowParams()

        # save to XML file
        vcp.SaveXML( savefile )

        # save D4Mat2Slicer params to XML file
        tt=TreatXmlParams(self)
        tt.add(savefile)
        del tt

        

    #################################
    def GetParamsForProj(self,isVect=False):
        """
        """
        sample=[]
        for cont in self.SampleInfoCtrl:
            anum = cont.GetValue().strip()
            if anum=="":
                anum = "0.0"
            try:
                num = float(anum)
            except:
                raise UtilPlot.PlotException('Common', 'C027', ("Sample Info",))
            sample.append(num)
        
        Header = {}
        Header['SimpleLatticeConsts']=sample[:6]
        Header['SampleUvec']=sample[6:9]
        Header['SampleVvec']=sample[9:12]
        
        rotationSteps=[]
        for i,rax in zip([0,1,2],self.chRotationSteps):
            if rax.IsEnabled():
                ax_num = rax.GetCurrentSelection()
                if ax_num == 1:
                    rotationSteps.append( ["Y", sample[12+i] ] )
                elif ax_num == 2:
                    rotationSteps.append( ["Z", sample[12+i] ] )
                elif ax_num == 3:
                    rotationSteps.append( ["X", sample[12+i] ] )
                else:
                    break
        Header['SampleRotateSteps']=rotationSteps
        
        # Make parameters to give to VisContParams
        ## axisInfo
        viewAxisInfo = []
        for id in range(4):
            a_list = []
            for col in range(4):
                a_list.append( float( self.ProjectionCtrl[id][col].GetValue() ) )
            a_list.append( self.ProjectionCtrl[id][4].GetValue() )
            viewAxisInfo.append(a_list)

        if isVect:
            LC = mm.MakeDoubleVector()
            UV = mm.MakeDoubleVector()
            VV = mm.MakeDoubleVector()
            for i in range(6):
                LC.append( sample[i] )
            for i in range(3):
                UV.append( sample[i+6] )
                VV.append( sample[i+9] )
            VA = mm.MakeDoubleVector()
            for i in range(4):
                for j in range(4):
                    VA.append( viewAxisInfo[i][j] )
            
            RV = mm.MakeDoubleVector()
            for i in range(3):
                if self.SampleInfoCtrl[12+i].IsEnabled():
                    axis_num = -1.0
                    if self.chRotationSteps[i].GetCurrentSelection()==1:   # if Y-axis
                        axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                    elif self.chRotationSteps[i].GetCurrentSelection()==2: # if Z-axis
                        axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                    elif self.chRotationSteps[i].GetCurrentSelection()==3: # if X-axis
                        axis_num = 0.0                             # 0 means X-axis in VisualCalcSqe
                    else:
                        break
                    if axis_num > -1.0:
                        RV.append( axis_num )                # axis number
                        RV.append( float( sample[12+i] ) )   # angle
                else:
                    break


            return (LC,UV,VV,VA,RV)
        else:
            return (Header,viewAxisInfo)



    #################################
    def OnOpenDataReduction(self, evt ):
        """
        """
        if self.DataReductionPanel!=None:
            try:
                self.DataReductionPanel.OnClose(None)
            except:
                pass
                
        #self.ShowMessage("OnOpenDataReduction")
        self.DataReductionPanel = DataReductionPanel(self.frame,self)

    #################################
    def GetProjectionParam(self): ## !! is useless dataRedParam ??
        """
        """
        #get Information
        (LC,UV,VV,VA,RV) = self.GetParamsForProj(isVect=True)

        Ei = 0.0
        dHW = 0.0
        hw_min = 0.0
        hw_max = 0.0
        if self.IsContinuousMethod:
            Ei = self.DataStoreContRot.Ei
            dHW = self.DataStoreContRot.HW_bin
            hw_min = self.DataStoreContRot.HW_min
            hw_max = self.DataStoreContRot.HW_max
        else:
            Ei = self.DataStoreStepByStep.Ei
            dHW = self.DataStoreStepByStep.HW_bin
            hw_min = self.DataStoreStepByStep.HW_min
            hw_max = self.DataStoreStepByStep.HW_max
        
        runNo = 0
        dataRedParam = mm.MakeDoubleVector()
        dataRedParam.append( 0.0 ) # Time slice begin
        dataRedParam.append( 0.0 ) # Time slice end
        dataRedParam.append( Ei ) # Ei
        dataRedParam.append( dHW ) # dHW
        dataRedParam.append( hw_min ) # hw_min
        dataRedParam.append( hw_max ) # hw_max
        dataRedParam.append( 0.0 ) # start angle degree
        dataRedParam.append( 0.0 ) # end angle degree
        dataRedParam.append( 0.0 ) # step angle degree
        if (self.IsContinuousMethod):
            runNo = self.DataStoreContRot.RunNo
            dataRedParam[0] = self.DataStoreContRot.TimeSliceStart # Time slice 
            dataRedParam[1] = self.DataStoreContRot.TimeSliceEnd   # Time slice
            dataRedParam[6] = self.DataStoreContRot.AngleStart # start angle degree
            dataRedParam[7] = self.DataStoreContRot.AngleEnd   # end angle degree
            dataRedParam[8] = self.DataStoreContRot.AngleStep # step angle degree
        return (runNo,dataRedParam,LC,UV,VV,VA,RV)

    #################################
    def OnDRExec(self,evt):
        """
        """
        #print( "OnDRExec event" )
        if self.IsContinuousMethod:
            if self.IsOnLineMode:
                print ("OnLine Mode")
            else:
                print ("Static Mode")
                self.DRContRotationStatic()
        else:
            print ("StepByStep Mode")
            self.DRStepByStep()
            #pass

    #################################        
    def DRContRotationStatic(self):
        """
        """
        self.ShowMessage("DataReductionOfContRotation")

        self.ButtonCtrlAfterDR(False)
        self.isEnableSlice=False       #[inamura 170228]
        self.CheckEnableSliceButton() #[inamura 170228]
        if isinstance( self.DataConverter, mu.UtsusemiEventDataConverterNeunet ):
            self.DataConverter.ResetHistogram()
        else:
            if (self.DataConverter != None):
                del self.DataConverter
            self.DataConverter = mu.UtsusemiEventDataConverterNeunet()
        
        st_Params = "hw,%f,%f,%f,%f"%( (self.DataStoreContRot.Ei,self.DataStoreContRot.HW_min,self.DataStoreContRot.HW_max,self.DataStoreContRot.HW_bin ) )
        runNo = self.DataStoreContRot.RunNo

        DU = D4Mat2Utils()
        if self.DataStoreContRot.Script!="":
            wfile,dfile = DU.MakeTempInfoFilesFromScript(runNo,
                                                         self.DataStoreContRot.Script,
                                                         self.DataStoreContRot.Ei,
                                                         self.DataStoreContRot.HW_min,
                                                         self.DataStoreContRot.HW_max,
                                                         self.DataStoreContRot.HW_bin,
                                                         self.DataStoreContRot.MaskFile )
        else:
            wfile,dfile = DU.MakeTempInfoFiles(runNo,st_Params)
        
        st_deg = self.DataStoreContRot.AngleStart
        ed_deg = self.DataStoreContRot.AngleEnd
        w_deg = self.DataStoreContRot.AngleStep
        t_start = self.DataStoreContRot.TimeSliceStart
        t_end = self.DataStoreContRot.TimeSliceEnd
        DU = D4Mat2Utils()
        cfile = DU.MakeCaseInfoFile( st_deg, ed_deg, w_deg, runNo )
        
        self.ShowMessage( "#### WiringInfo.xml=%s"%wfile )
        self.ShowMessage( "#### DetectorInfo.xml=%s"%dfile )
        self.ShowMessage( "#### CaseInfo.xml=%s"%cfile )
        
        data_dir = "/data"
        
        self.DataConverter.LoadParamFiles( wfile, dfile, cfile )

        if t_start<0 and t_end<0:
            pass
        else:
            if not self.DataConverter.SetRangeOfSingleTimeSlicing( t_start, t_end ):
                msg = "TimeSlicing arguments are invalid : "+str(t_start)+","+str(t_end)
                raise UserWarning, msg

        self.DataConverter.LoadTrignetEventFile( runNo, data_dir, "" )
        #self.DataConverter.SetHistAllocation()
        self.DataConverter.SetHistAllocation(1)
        self.DataConverter.LoadEventDataFiles( runNo, data_dir, "" )

        ## Turn On Project Button on MainPanel
        self.IsReadyProjection = True
        self.ButtonCtrlList[0].Enable(self.IsReadyProjection)

    #################################
    def DRStepByStep(self):
        """
        """
        self.ShowMessage("DRStepByStep")
        self.ButtonCtrlAfterDR(False)
        self.isEnableSlice=False
        self.CheckEnableSliceButton()

        try:
            dam = self.DataReductionPanel.lstRunInfo.GetItemCount()
        except:
            self.DataReductionPanel = DataReductionPanel(self.frame,self)
        for gonio_key in self.RunList: # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
            ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[gonio_key]
            self.RunList[gonio_key] = (1, ex_runs, ex_angle, ex_protons, ex_ind)
            self.DataReductionPanel.lstRunInfo.SetItemImage(ex_ind, 1)
        self.D4MatR.ClearAll()
        self.ExecDataReductionStepByStep.OnStart(self.DataStoreStepByStep, self.D4MatR, self.RunList)

        # 実行状態を監視するために、0.5秒毎のタイマーをセット 
        self.timer = wx.Timer(self.frame)
        self.timer.Start(500)
        self.frame.Bind(wx.EVT_TIMER, self.OnTimerStepByStep, self.timer)

    #################################
    def OnTimerStepByStep(self,evt):
        """
        """
        if self.ExecDataReductionStepByStep.status==-1:
            for i in range( self.DataReductionPanel.lstRunInfo.GetItemCount() ):
                self.DataReductionPanel.lstRunInfo.SetItemImage(i,3)
            self.timer.Stop()
            self.IsReadySlice = True
            for gonio_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[gonio_key]
                self.RunList[gonio_key] = (3, ex_runs, ex_angle, ex_protons, ex_ind)
                self.ButtonCtrlAfterDR(True)
        else:
            for i in range(self.ExecDataReductionStepByStep.index):
                self.DataReductionPanel.lstRunInfo.SetItemImage(i, 3)
            self.DataReductionPanel.lstRunInfo.SetItemImage(self.ExecDataReductionStepByStep.index, 2)

    #################################
    def ButtonCtrlAfterDR(self, flag):
        """
        """
        # Projection is controled
        self.ButtonCtrlList[0].Enable(flag)
        self.ButtonCtrlList[1].Enable(flag)
        # Out to SPE is controled
        self.ButtonCtrlList[8].Enable(flag)
        # Autofills are disabled
        self.ButtonCtrlList[2].Enable(False)
        self.ButtonCtrlList[3].Enable(False)
        self.ButtonCtrlList[4].Enable(False)
        self.ButtonCtrlList[5].Enable(False)
        self.ButtonCtrlList[6].Enable(False)
        # Output are disabled
        self.ButtonCtrlList[7].Enable(False)

    #################################
    def ButtonCtrlAfterProj(self, flag):
        """
        """
        # All buttons are controled
        for bt in self.ButtonCtrlList:
            bt.Enable(flag)

    #################################
    def OnProjForAll(self,evt):
        """
        """
        self.ShowMessage("OnProjForAll")

        runNo,DRP,LC,UV,VV,VA,RV = self.GetProjectionParam()
        self.D4MatR.SetD4MatSampleInfo( LC, UV, VV, RV )
        self.D4MatR.SetD4MatDataReductionInfo( DRP )
        if not self.IsContinuousMethod:
            self.D4MatR.ProjectionStepByStep( VA )
            self.ButtonCtrlAfterProj(True)
            self.isEnableSlice=True
            self.CheckEnableSliceButton()
            return

        self.D4MatR.SetD4MatRunNo( runNo )
        self.D4MatR.SetD4MatProjectionAxesInfo( VA )
        self.ExecProjectionContRot.OnStart(self.DataConverter, self.D4MatR, self.DataStoreContRot)

        # 実行状態を監視するために、0.5秒毎のタイマーをセット 
        self.timer = wx.Timer(self.frame)
        self.timer.Start(500)
        self.frame.Bind(wx.EVT_TIMER, self.OnTimerContRot, self.timer)

        self.ButtonCtrlAfterProj(True)
        self.isEnableSlice=True
        self.CheckEnableSliceButton()

    #################################
    def OnTimerContRot(self,evt):
        """
        """
        if self.ExecProjectionContRot.status==-1:
            self.timer.Stop()
            self.IsReadySlice = True
        else:
            pass
        return

    #################################
    def OnProjClearAll(self,evt):
        """
        """
        self.ShowMessage("OnProjClearAll")
        #for run in self.RunList:
        #    run.Status=1
        
        #clear D4mat
        self.D4MatR.ResetD4mat();

    #################################[inamura 170215]-->
    def OnChangeDiagFold(self,evt):
        """
        """
        self.ShowMessage("OnChangeDiagFold is not working (under constructions)")

    #################################
    def OnAutoFill(self,evt):
        """
        """
        self.ShowMessage("OnAutoFill")
        limit_vec = self.D4MatR.GetAxLimit()
        self.ShowMessage("limit Ax1= %f,%f"%(limit_vec[0],limit_vec[1]))
        self.ShowMessage("limit Ax2= %f,%f"%(limit_vec[2],limit_vec[3]))
        self.ShowMessage("limit Ax3= %f,%f"%(limit_vec[4],limit_vec[5]))
        self.ShowMessage("limit Ax4= %f,%f"%(limit_vec[6],limit_vec[7]))
        for i in range(4):
            self.SliceRange[i*3].SetValue( "%7.3f" %(limit_vec[i*2]) )
            self.SliceRange[i*3+1].SetValue( "%7.3f"%(limit_vec[i*2+1]) )
                
    #########################################
    def OnAutoFillAxes(self,*args):
        try:
            btn_name = args[0].GetEventObject().GetName()
            limit_vec = self.D4MatR.GetAxLimit()
            if btn_name == "btAutoFillAx1":
                self.SliceRange[0].SetValue( "%7.3f" % (limit_vec[0]) )
                self.SliceRange[1].SetValue( "%7.3f" % (limit_vec[1]) )
            elif btn_name == "btAutoFillAx2":
                self.SliceRange[3].SetValue( "%7.3f" % (limit_vec[2]) )
                self.SliceRange[4].SetValue( "%7.3f" % (limit_vec[3]) )
            elif btn_name == "btAutoFillAx3":
                self.SliceRange[6].SetValue( "%7.3f" % (limit_vec[4]) )
                self.SliceRange[7].SetValue( "%7.3f" % (limit_vec[5]) )
            elif btn_name == "btAutoFillAx4":
                self.SliceRange[9].SetValue( "%7.3f" % (limit_vec[6]) )
                self.SliceRange[10].SetValue( "%7.3f" % (limit_vec[7]) )
            else:
                pass
        except:
            self.ShowMessage("Do the projection first")
        
    #################################
    def OnChangeSliceAxis(self,evt):
        """
        """
        bt = evt.GetEventObject()

        # Get control of step in axis ranges
        step_ctrl = None
        for i in range(4):
            if bt==self.SliceAxis[i]:
                step_ctrl = self.SliceRange[i*3 +2]
                    
        # Set step control visible or invisible
        if bt.GetCurrentSelection()==2: # 0..X-Axis, 1..Y-Axis, 2..Thickness
            step_ctrl.Enable(False)
        else:
            step_ctrl.Enable(True)

        self.CheckEnableSliceButton() ##[inamura 170228]

    #########################################
    def CheckEnableSliceButton(self):
        """
        """
        if self.isEnableSlice:
            flags = [0,0,0,0]
            for i in range(4):
                curNo = self.SliceAxis[i].GetCurrentSelection()
                flags[curNo] +=1
            if flags==[1,1,2,0]:
                self.SliceButtonCtrlList[0].Enable(True)
                self.SliceButtonCtrlList[1].Enable(False)
            elif flags==[1,1,1,1]:
                self.SliceButtonCtrlList[0].Enable(False)
                self.SliceButtonCtrlList[1].Enable(True)
            else:
                self.SliceButtonCtrlList[0].Enable(False)
                self.SliceButtonCtrlList[1].Enable(False)
        else:
            self.SliceButtonCtrlList[0].Enable(False)
            self.SliceButtonCtrlList[1].Enable(False)

    #########################################
    def OnSlice(self,*args):
        """
        """
        self.ShowMessage("OnSlice")
        if self.IsReadySlice:
            self.SliceContRotData()

        else:
            raise UserWarning, "Data Reduction is not done"
            
    #################################
    def SliceContRotData(self,isRefresh=True):
        """
        """
        
        #get slice params
        (VS1,VS2,VS3,VS4,VST,VSF) = self.GetParamsForSlice(isVect=True)

        flag=[0,0,0]
        for i in range(4):
            if VST[i]=="x":
                flag[0] += 1
            if VST[i]=="y":
                flag[1] += 1
            if VST[i]=="t":
                flag[2] += 1
        if (flag[0]!=1) or (flag[1]!=1) or (flag[2]!=2):
            self.ShowMessage("SliceContRotDat: Invalid Axis info X,Y,T")
            return
        
        #slice
        eca_ret = self.D4MatR.Slice2d( VS1, VS2, VS3, VS4, VST, VSF )

        titles = ["","","","",""]
        titles[0]="D4MatR Slice"
        for i in range(4):
            label = self.ProjectionCtrl[i][4].GetValue()
            if VST[i]=="x":
                titles[2]=label
            elif VST[i]=="y":
                titles[3]=label
            else:
                titles[1] += "Ax%d:%s\n" % (i+1,label)
                titles[1] += " from %s to %s\n" % (self.SliceRange[i*3].GetValue(),self.SliceRange[i*3+1].GetValue())
        titles[4] = "Intensity"
        
        if self.M2Plot==None:
            self.M2Plot = Plot2DMap(0, "D4MatRSlicer", self.frame)
            
        self.M2Plot.PlotMap( titles, eca_ret, isRefresh )

    #################################
    def OnMakeD4MatFile(self,evt):
        """
        """
        self.ShowMessage("OnMakeD4MatFile")
        
        #get slice params
        (VS1,VS2,VS3,VS4,VST,VSF) = self.GetParamsForSlice(isVect=True)
        ax_Titles = mm.MakeStringVector()
        for i in range(4):
            print "Ax%d = %s"%(i,self.ProjectionCtrl[i][4].GetValue())
            ax_Titles.push_back(str(self.ProjectionCtrl[i][4].GetValue()))
        
        print "VS1=",VS1[0],VS1[1],VS1[2],VS1[3]
        print "VS2=",VS2[0],VS2[1],VS2[2],VS2[3]
        print "VS3=",VS3[0],VS3[1],VS3[2],VS3[3]
        print "VS4=",VS4[0],VS4[1],VS4[2],VS4[3]
        print "VST=",VST[0],VST[1],VST[2],VST[3]
        print "Title=%s,%s,%s,%s"%(ax_Titles[0],ax_Titles[1],ax_Titles[2],ax_Titles[3])
        
        # open directory dialog
        dlg = wx.FileDialog( self.frame, 'Choose File to save D4Mat data  ...', defaultDir=os.getcwd(), defaultFile='D4Mat.xml', wildcard='D4Mat File(*.xml)|*.xml',style=wx.SAVE )
        
        # cancel?
        if dlg.ShowModal() != wx.ID_OK:
            return
        
        # get path
        filepath = dlg.GetPath()
        dir_path = str(os.path.dirname(filepath))
        paramfile = str(os.path.basename(filepath))
        self.D4MatR.AllocateD4MatOnDisk( VS1, VS2, VS3, VS4, ax_Titles, dir_path, paramfile )

    #################################
    def OnConvSPEFiles(self,evt):
        """
        """
        self.ShowMessage("OnConvSPEFiles")

        #import ana.Reduction.DefaultInstParams as DFI
        #L2 = DFI.Def_L2*1000.0     # [mm]
        #dS = DFI.Def_dS        # [mm]
        hh = mm.HeaderBase()
        L2 = 1.0
        dS = 1.0
        if self.DataConverter.AddRunInfoToHeader(hh):
            L2 = hh.PutDouble("TypicalL2")
            dS = hh.PutDouble("TypicalDS")
        dOmega = dS/(L2*L2)
        mask_file = self.DataStoreContRot.MaskFile
        mask_path = self.DataStoreContRot.MaskFile
        if not os.path.exists( mask_path ):
            if os.environ.has_key("UTSUSEMI_USR_DIR"):
                mask_path = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",mask_file)
                if not os.path.exists( mask_path ):
                    if os.environ.has_key("UTSUSEMI_USR_PRIV_HOME"):
                        mask_path = os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",mask_file)
                        if not os.path.exists( mask_path ):
                            mask_path = os.path.join(os.environ["HOME"],"ana","xml",mask_file)
                            if not os.path.exists( mask_path ):
                                mask_path = ""

        dlg = wx.DirDialog(self.frame, "Choose Directory to save SPE files ...",os.getcwd())
        if dlg.ShowModal() !=wx.ID_OK:
            return

        #check selected dir
        target_folder = str(dlg.GetPath())
        if not os.path.exists( target_folder ):
            print self.CommnetHead + "Cannot find such directory, "+target_folder
            raise

        #
        import ana.Reduction.BaseCommandsInEla as BC
        if self.IsContinuousMethod:
            cond_list = self.DataConverter.PutListOfCounterConditions()
            num_of_cases = self.DataConverter.PutCaseDecoder()._NumOfCases
            runNo = self.DataStoreContRot.RunNo
            instCode = os.environ["UTSUSEMI_SYS_NAME"]
            fname_tmp = "%3s%06d_%g" ## %(instCode, runNo, Phi)
            for i in range(num_of_cases):
                caseId = i+1
                phi = (cond_list[(i+1)*2] + cond_list[(i+1)*2 +1])/2.0

                ecm = mm.ElementContainerMatrix()
                self.DataConverter.SetElementContainerMatrix( ecm, caseId )

                URI = mu.UtsusemiReductionInEla(ecm)
                URI.CalcPhi()

                if mask_path!="":
                    MSK = mm.UtsusemiSetMask(ecm, mask_path)
                    MSK.Execute()
                    del MSK
                for j in range( ecm.PutSize() ):
                    if ecm(j).PutHeaderPointer().PutString("TYPE")=="PSD":
                        for k in range( ecm(j).PutSize() ):
                            ec = ecm(j,k)
                            sol_ang = ec.PutHeaderPointer().PutDouble("PixelSolidAngle")/dS
                            if sol_ang!=0.0:
                                ec.MulMySelf( 1.0/sol_ang )

                URI.KiKfCorrect()
                del URI

                if ecm.PutHeaderPointer().CheckKey("KICKERCOUNT")==1:
                    cnt = float( ecm.PutHeaderPointer().PutInt4("KICKERCOUNT") )
                    if cnt!=0.0:
                        ecm.MulMySelf( 1.0/cnt )

                ecm.AddToHeader("PHI",phi)
                BC.SaveDataToSPE(ecm, path=target_folder,filename=(fname_tmp%(instCode,runNo,Phi)))
        else: # Step by Step
            instCode = os.environ["UTSUSEMI_SYS_NAME"]
            for gonio_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[gonio_key]
                ecm = mm.ElementContainerMatrix()
                self.D4MatR.ExportEcmFromStepByStep( ecm, ex_ind )
                fname = "%3s_%s"%(instCode,gonio_key)
                BC.SaveDataToSPE(ecm, path=target_folder,filename=fname)
                del ecm

    #################################
    def OnSlice3D(self,evt):
        """
        """
        self.ShowMessage("OnSlice3D")
        
        #get slice params
        (VS1,VS2,VS3,VS4,VST,VSF) = self.GetParamsForSlice(isVect=True)
        print "VS1=",VS1[0],VS1[1],VS1[2],VS1[3]
        print "VS2=",VS2[0],VS2[1],VS2[2],VS2[3]
        print "VS3=",VS3[0],VS3[1],VS3[2],VS3[3]
        print "VS4=",VS4[0],VS4[1],VS4[2],VS4[3]
        print "VST=",VST[0],VST[1],VST[2],VST[3]

        flag=[0,0,0,0]
        titles_org = ["X","Y","Z"]
        for i in range(4):
            if VST[i]=="x":
                flag[0] += 1
                titles_org[0] = self.ProjectionCtrl[i][4].GetValue()
            if VST[i]=="y":
                flag[1] += 1
                titles_org[1] = self.ProjectionCtrl[i][4].GetValue()
            if VST[i]=="z":
                flag[2] += 1
                titles_org[2] = self.ProjectionCtrl[i][4].GetValue()
            if VST[i]=="t":
                flag[3] += 1
        if (flag[0]!=1) or (flag[1]!=1) or (flag[2]!=1) or (flag[3]!=1):
            self.ShowMessage("OnSlice: Invalid Axis info X,Y,T")
            return
        
        #slice
        ecm_ret = self.D4MatR.Slice3d( VS1, VS2, VS3, VS4, VST, VSF )

        #plot
        import vis.SliceViewer3D as SV
        if self.SliceViewer3d==None:
            self.SliceViewer3d = SV.SliceViewer()
        if self.SliceViewer3d.setData( 0, ecm_ret, "Sliced data in D4Mat2Slicer" ):
            pass
        else:
            del self.SliceViewer3d
            self.SliceViewer3d = SV.SliceViewer()
            self.SliceViewer3d.setData( 0, ecm_ret, "Sliced data in D4Mat2Slicer" )

        titles = []
        for a_title in titles_org:
            titles.append( a_title.replace(" ","") )
        self.SliceViewer3d.setAxesTitles( titles[0], titles[1], titles[2] )

#################################
    def GetParamsForSlice(self,isVect=False):
        """
        """
        dic_axis = {0:"x",1:"y",2:"t",3:"z"}
        dic_fold = { False:0, True:1 }
        type_list = []
        fold_list = []
        for i in range(4):
            type_list.append( dic_axis[ self.SliceAxis[i].GetCurrentSelection() ] )
            fold_list.append( float(self.SliceFold[i].GetValue() ) )

        sliceInfo = []
        for id in range(4):
            a_list = [type_list[id]]
            for i in range(3):
                a_list.append( float( self.SliceRange[3*id + i].GetValue() ) )
            a_list.append( fold_list[id] )
            sliceInfo.append( a_list )

        if isVect:
            VS1 = mm.MakeDoubleVector()
            VS2 = mm.MakeDoubleVector()
            VS3 = mm.MakeDoubleVector()
            VS4 = mm.MakeDoubleVector()
            VST = mm.MakeStringVector()
            VSF = mm.MakeDoubleVector()
            for i in range(4):
                VS1.append( sliceInfo[0][i+1] )
                VS2.append( sliceInfo[1][i+1] )
                VS3.append( sliceInfo[2][i+1] )
                VS4.append( sliceInfo[3][i+1] )
                VST.append( type_list[i] )
                VSF.append( fold_list[i] )
            return (VS1,VS2,VS3,VS4,VST,VSF)
        else:
            return sliceInfo

    #################################
    def OnClickOnLineMode(self,evt):
        """
        """
        #print( "OnClickOnLineMode event" )
        isToggleOn = self.OnLineModeBtn.GetValue()

        if self.DataConverter!=None:
            #msg = "%s "%(type(self.DataConverter))
            msg = ""
            if isinstance( self.DataConverter, mu.UtsusemiEventDataConverterNeunet ):
                msg += "Now we are in not-online-mode. To move online-mode, data will be cleared. OK?"
            else:
                msg += "Now we are in auto-update-mode. To move no-online-mode, data will be destroyed. OK?"
            
            dlg = wx.MessageDialog(None, msg, "Warning", wx.YES_NO|wx.NO_DEFAULT|wx.ICON_EXCLAMATION )
            if dlg.ShowModal() !=wx.ID_YES:
                self.OnLineModeBtn.SetValue( not isToggleOn )
                return
            self.D4MatR.ResetD4mat()
            del self.DataConverter
            self.DataConverter = None
            if self.IsAutoUpdateMode:
                self.IsAutoUpdateMode = False
            
        if isToggleOn:
            self.BtnReductionInfo.Enable(False)
            self.BtnDRExec.Enable(False)
            print "isToggleOn is True"
            self.DataConverter = mu.UtsusemiEventDataMonitorNeunet()
            self.doneOnLineModeFirstPrmSet = False
        else:
            self.BtnReductionInfo.Enable(True)
            self.BtnDRExec.Enable(True)
            print "isToggleOn is False"
            self.DataConverter = None

        for a_item in self.OnLineModeBtnCtrlList:
            a_item.Enable( isToggleOn )
        for a_item in self.OnLineModeCkbCtrlList[1:]:
            a_item.Enable( isToggleOn )
        self.AUIntervalTimeTxt.Enable( isToggleOn )
        self.AUIntervalUnit.Enable( isToggleOn )

        self.IsOnLineMode = isToggleOn

    #################################
    def OnAUupdate(self,evt):
        """
        """
        #print( "OnAUupdate event" )
        if not self.doneOnLineModeFirstPrmSet:
            st_Params = "hw,%f,%f,%f,%f"%( (self.DataStoreContRot.Ei,self.DataStoreContRot.HW_min,self.DataStoreContRot.HW_max,self.DataStoreContRot.HW_bin ) )
            runNo = self.DataStoreContRot.RunNo
            DU = D4Mat2Utils()
            if self.DataStoreContRot.Script!="":
                wfile,dfile = DU.MakeTempInfoFilesFromScript(runNo,
                                                             self.DataStoreContRot.Script,
                                                             self.DataStoreContRot.Ei,
                                                             self.DataStoreContRot.HW_min,
                                                             self.DataStoreContRot.HW_max,
                                                             self.DataStoreContRot.HW_bin,
                                                             self.DataStoreContRot.MaskFile )
            else:
                wfile,dfile = DU.MakeTempInfoFiles(runNo,st_Params)

            st_deg = self.DataStoreContRot.AngleStart
            ed_deg = self.DataStoreContRot.AngleEnd
            w_deg = self.DataStoreContRot.AngleStep
            t_start = self.DataStoreContRot.TimeSliceStart
            t_end = self.DataStoreContRot.TimeSliceEnd
            DU = D4Mat2Utils()
            cfile = DU.MakeCaseInfoFile( st_deg, ed_deg, w_deg, runNo )
            self.DataConverter.SetRunNumber( runNo )
            self.DataConverter.SetDataFolder( "/data" )
            self.DataConverter.ParameterSet( wfile,dfile,cfile, 1 )
            self.DataConverter.AddAllDataModules()
            self.doneOnLineModeFirstPrmSet = True
            self.D4MatR.ResetD4mat()
            self.doneD4MatPrmSet = False
            
        if self.OnLineModeCkbCtrlList[0].GetValue():
            self.ShowMessage("--UpdateDataModules--")
            self.DataConverter.UpdateDataModules()
            self.ShowMessage("--IncrementCases--")
            if self.DataConverter.IncrementCases():
                self.ShowMessage("--Increment--")
                self.DataConverter.Increment()
                self.IsReadyProjection = True
                self.ButtonCtrlList[0].Enable(self.IsReadyProjection)
            
        if self.OnLineModeCkbCtrlList[1].GetValue():
            runNo,DRP,LC,UV,VV,VA,RV = self.GetProjectionParam()
            if not self.doneD4MatPrmSet:
                self.D4MatR.SetD4MatSampleInfo( LC, UV, VV, RV )
                self.D4MatR.SetD4MatDataReductionInfo( DRP )
                self.D4MatR.SetD4MatRunNo( runNo )
                self.D4MatR.SetD4MatProjectionAxesInfo( VA )
                self.D4MatR.AllocateD4MatPseudoOnLine( self.DataConverter.PutNumOfCases() )
                self.doneD4MatPrmSet = True
            cond_list = self.DataConverter.PutListOfCounterConditions()
            
            self.ProjContRot=ExecProjectionContRot(self.lock,True)
            self.ShowMessage("--Projection--")
            self.ProjContRot.OnStart(self.DataConverter, self.D4MatR, self.DataStoreContRot)
            self.IsReadySlice = True
            
            if self.OnLineModeCkbCtrlList[2].GetValue():
                if type(evt)==bool and evt==True:
                    while( self.ProjContRot.num_of_updated != self.ProjContRot.index ):
                        time.sleep(0.5)
                    self.SliceContRotData(isRefresh=False)
            else:
                for a_btn in self.ButtonCtrlList[2:]:
                    a_btn.Enable(True)
                self.isEnableSlice=True
                self.CheckEnableSliceButton()

            
            
    #################################
    def OnAUstart(self,evt):
        """
        """
        
        #print( "OnAUstart event" )
        
        if (self.IsAutoUpdateMode):
            self.ShowMessage("[AutoUpdate]--FINISHED--")
            self.IsAutoUpdateMode = False
            self.OnLineModeBtnCtrlList[0].Enable(True)
            self.OnLineModeBtnCtrlList[1].SetLabel("Interval Start")
            self.AUIntervalTimeTxt.Enable(True)
        else:
            self.OnLineModeBtnCtrlList[0].Enable(False)
            self.OnLineModeBtnCtrlList[1].SetLabel("Stop")
            self.OnAUupdate(True)
            self.IsAutoUpdateMode = True
            self.ShowMessage("[AutoUpdate]--START--")
            update_sec = float( self.AUIntervalTimeTxt.GetValue() )
            if (update_sec<10.0):
                return
            self.AUIntervalTimeTxt.Enable(False)
            
            self.timer_online = wx.Timer(self.frame)
            self.timer_online.Start(int(update_sec)*1000)
            self.frame.Bind(wx.EVT_TIMER, self.OnAutoUpdate, self.timer_online)
            

    #################################
    def OnAutoUpdate(self,evt):
        """
        """
        if self.IsAutoUpdateMode:
            if self.OnLineModeCkbCtrlList[2].GetValue():
                if self.ProjContRot.num_of_updated == self.ProjContRot.index:
                    self.SliceContRotData(isRefresh=False)

            if self.OnLineModeCkbCtrlList[0].GetValue():
                if self.ProjContRot.num_of_updated == self.ProjContRot.index:
                    self.ShowMessage("[AutoUpdate]--UpdateDataModules--")
                    self.DataConverter.UpdateDataModules()
                else:
                    self.ShowMessage("[AutoUpdate]--Pause UpdateDataModules--")
                    return
                self.ShowMessage("[AutoUpdate]--IncrementCases--")
                if self.DataConverter.IncrementCases():
                    self.ShowMessage("[AutoUpdate]--Increment--")
                    self.DataConverter.Increment()
                    self.IsReadyProjection = True
                    self.ButtonCtrlList[0].Enable(self.IsReadyProjection)
                    
                    if self.OnLineModeCkbCtrlList[1].GetValue():
                        if self.ProjContRot.num_of_updated == self.ProjContRot.index:
                            runNo,DRP,LC,UV,VV,VA,RV = self.GetProjectionParam()

                            self.D4MatR.SetD4MatSampleInfo( LC, UV, VV, RV )
                            self.D4MatR.SetD4MatDataReductionInfo( DRP )
                            self.D4MatR.SetD4MatRunNo( runNo )
                            self.D4MatR.SetD4MatProjectionAxesInfo( VA )

                            del self.ProjContRot
                            self.ProjContRot=ExecProjectionContRot(self.lock,True)
                            self.ShowMessage("[AutoUpdate]--Projection--")
                            self.ProjContRot.OnStart( self.DataConverter, self.D4MatR, self.DataStoreContRot)
        
        else:
            self.timer_online.Stop()
            

    #################################
    def OnAUwithReduction(self,evt):
        """
        """
        #print( "OnAUwithReduction event" )
        flag = not evt.IsChecked()
        self.BtnReductionInfo.Enable(flag)
        self.BtnDRExec.Enable(flag)


    #################################
    def OnAUwithProjection(self,evt):
        """
        """
        #print( "OnAUwithProjection event" )
        isEnable = True
        if evt.IsChecked():
            isEnable = False

        for a_item in self.SampleInfoCtrl:
            a_item.Enable( isEnable )
        for a_item in self.chRotationSteps:
            a_item.Enable( isEnable )
        if isEnable:
            self.OnChoiceRotateAxes2()
        for item_list in self.ProjectionCtrl:
            for a_item in item_list:
                a_item.Enable( isEnable )
        # if already done reduction ##[inamura 170215]
        if isEnable:
            self.ButtonCtrlList[0].Enable(self.IsReadyProjection)
        else:
            self.ButtonCtrlList[0].Enable(False)

    #################################
    def OnAUwithSlice(self,evt):
        """
        """
        #print( "OnAUwithSlice event" )
        isEnable = True
        if evt.IsChecked():
            isEnable = False
        for a_item in self.SliceAxis:
            a_item.Enable( isEnable )
        for a_item in self.SliceRange:
            a_item.Enable( isEnable )
        for a_item in self.SliceFold:
            a_item.Enable( isEnable )
        for i in range(2,8):
            self.ButtonCtrlList[i].Enable( isEnable )
        self.DiagFoldType.Enable( isEnable )
        self.isEnableSlice=isEnable
        self.CheckEnableSliceButton()
        
    #########################################
    def OnChoiceRotateAxes2(self, evt=None):
        """
        """
        if self.chrotax1.GetCurrentSelection()==0:
            self.SampleInfoCtrl[12].Enable(False)
            self.chrotax2.Enable(False)
            self.SampleInfoCtrl[13].Enable(False)
            self.chrotax3.Enable(False)
            self.SampleInfoCtrl[14].Enable(False)
        else:
            self.SampleInfoCtrl[12].Enable(True)
            self.chrotax2.Enable(True)
            if self.chrotax2.GetCurrentSelection()==0:
                self.SampleInfoCtrl[13].Enable(False)
                self.chrotax3.Enable(False)
                self.SampleInfoCtrl[14].Enable(False)
            else:
                self.SampleInfoCtrl[13].Enable(True)
                self.chrotax3.Enable(True)
                if self.chrotax3.GetCurrentSelection()==0:
                    self.SampleInfoCtrl[14].Enable(False)
                else:
                    self.SampleInfoCtrl[14].Enable(True)

    #########################################
    def OnChoiceRotateAxes(self, evt):
        """
        CHOICE Event
        ##[inamura 150526]
        @param evt    Event
        @retval None
        """
        bt = evt.GetEventObject()
        if bt==self.chrotax1:
            if self.chrotax1.GetCurrentSelection()==0:
                self.SampleInfoCtrl[12].Enable(False)
                self.chrotax2.Enable(False)
                self.SampleInfoCtrl[13].Enable(False)
                self.chrotax3.Enable(False)
                self.SampleInfoCtrl[14].Enable(False)
            else:
                self.SampleInfoCtrl[12].Enable(True)
                self.chrotax2.Enable(True)
                if self.chrotax2.GetCurrentSelection()==0:
                    self.SampleInfoCtrl[13].Enable(False)
                    self.chrotax3.Enable(False)
                    self.SampleInfoCtrl[14].Enable(False)
                else:
                    self.SampleInfoCtrl[13].Enable(True)
                    self.chrotax3.Enable(True)
                    if self.chrotax3.GetCurrentSelection()==0:
                        self.SampleInfoCtrl[14].Enable(False)
                    else:
                        self.SampleInfoCtrl[14].Enable(True)

        elif bt==self.chrotax2:
            if self.chrotax1.GetCurrentSelection()==0:
                self.SampleInfoCtrl[13].Enable(False)
                self.chrotax3.Enable(True)
                self.SampleInfoCtrl[14].Enable(False)
            else:
                if bt.GetCurrentSelection()==0:
                    self.SampleInfoCtrl[13].Enable(False)
                    self.chrotax3.Enable(False)
                    self.SampleInfoCtrl[14].Enable(False)
                else:
                    self.chrotax3.Enable(True)
                    self.SampleInfoCtrl[13].Enable(True)
                    if self.chrotax3.GetCurrentSelection()==0:
                        self.SampleInfoCtrl[14].Enable(False)
                    else:
                        self.SampleInfoCtrl[14].Enable(True)

        else:
            if (self.chrotax1.GetCurrentSelection()==0) or (self.chrotax2.GetCurrentSelection()==0) or (bt.GetCurrentSelection()==0):
                self.SampleInfoCtrl[14].Enable(False)
            else:
                self.SampleInfoCtrl[14].Enable(True)

    def ShowMessage(self,msg):
        """
        """
        # below script leads error (Core Dump or Error in python free() invalid size
        #from datetime import datetime as dt
        #time_now = dt.now()
        #time_st = time_now.strftime("[%Y/%m/%d %H:%M:%S]")
        time_st = ""
        print( time_st+" D4Mat2Slicer >>"+msg )

class D4Mat2Utils(object):
    """
    """
    def __init__(self):
        """
        """
        # Key of arguments for Histgram
        self.HSTKEY_HistParam ="HistParam"
        self.HSTKEY_DetParam  ="DetParam"
        self.HSTKEY_DetRange  ="DetRange"
        self.HSTKEY_TimeRange ="TimeRange"
        self.HSTKEY_FrameInfo ="FrameInfo"
        self.HSTKEY_MaskInfo  ="MaskInfo"
        self.HSTKEY_CaseInfo  ="CaseInfo"
        self.HSTKEY_BGInfo    ="BGInfo"
        self.HSTKEY_TofShift  ="TofShift"
        self.HSTKEY_AnaMode   ="AnaMode"
        self.HSTKEY_Options   ="Options"

    #################################
    def MakeTempInfoFiles(self,runNo,params):
        """
        """
        hh = mu.UtsusemiGetNeunetHistogram()
        hh.SetRunNo( runNo )
        hh.SetConversionParameter( params )
        print( "D4Mat2Utils::MakeTempInfoFiles >> st_Params=%s"%params )
        hh.SetDetParam( "PSD,TRIGNET" )
        tmp_files = hh.MakeTempInfoFiles()
        return (tmp_files[0],tmp_files[1])
        
    #################################
    def MakeTempInfoFilesFromScript(self,runNo,script_path,_Ei,_HW_min,_HW_max,_HW_bin,_MaskFile):
        """
        """
        print("D4Mat2Utils::MakeTempInfoFilesFromScript")
        p_dic = self.GetHistogramParamsFromScript(script_path,_Ei,_HW_min,_HW_max,_HW_bin,_MaskFile)
        if p_dic==None:
            return None
        
        hh = mu.UtsusemiGetNeunetHistogram()
        
        (flag,param) = p_dic[self.HSTKEY_AnaMode]
        if flag:
            ana_mode_list = param.split(",")
            if len(ana_mode_list)==1:
                hh.SetRunNo( runNo, aan_mode_list[0] )
            elif len(ana_mode_list)==3:
                pfiles = "%s,%s"%(ana_mode_list[1].strip(), ana_mode_list[2].strip())
                if pfiles=="-,-":
                    hh.SetRunNo( runNo, ana_mode_list[0] )
                else:
                    hh.SetRunNo( runNo, pfiles[0],pfiles[1], ana_mode_list[0] )
        else:
            hh.SetRunNo( runNo )
                
        (flag,param) = p_dic[self.HSTKEY_HistParam]
        hh.SetConversionParameter( param )

        (flag,param) = p_dic[self.HSTKEY_DetParam]
        if flag:
            hh.SetDetParam( param )
        (flag,param) = p_dic[self.HSTKEY_DetRange]
        if flag:
            hh.SetDetRange( param )
        (flag,param) = p_dic[self.HSTKEY_TimeRange]
        if flag:
            hh.SetTimeRange( param )
        (flag,param) = p_dic[self.HSTKEY_FrameInfo]
        if flag:
            hh.SetFrameInfo( param )
        (flag,param) = p_dic[self.HSTKEY_MaskInfo]
        if flag:
            hh.SetMaskInfo( param )

        (flag,param) = p_dic[self.HSTKEY_CaseInfo]
        if flag:
            hh.SetCaseInfo( param )
        (flag,param) = p_dic[self.HSTKEY_BGInfo]
        if flag:
            if param.upper().find("TIMEDEP:")<0:
                pass
            else:
                ind = param.upper().find("TIMEDEP:")
                param = param[(ind+8):]
                hh.SetTimeDependBackGroundInfo(param)
        (flag,param) = p_dic[self.HSTKEY_TofShift]
        if flag:
            hh.SetTofShiftInfo( param )
        (flag,param) = p_dic[self.HSTKEY_Options]
        if flag:
            options_list = Options.split(",")
            sx = 0.0
            sy = 0.0
            sz = 0.0
            for a_option in options_list:
                tmp = a_option.strip().upper()
                if tmp.find("ISCHECKPULSEID:")==0:
                    if tmp[15:]=="FALSE":
                        UGH.SetFlagOfPulseIdCheck(False)
                    elif tmp[15:]=="TRUE":
                        UGH.SetFlagOfPulseIdCheck(True)
                elif tmp.find("ADDTOFBIN:")==0:
                    if tmp[10:]=="TRUE":
                        UGH.SetFlagToAddTofBin(True)
                elif tmp.find("L1:")==0:
                    UGH.SetL1( float(tmp[3:]) ) # [mm]
                elif tmp.find("SX:")==0:
                    sx = float( tmp[3:] )
                elif tmp.find("SY:")==0:
                    sy = float( tmp[3:] )
                elif tmp.find("SZ:")==0:
                    sz = float( tmp[3:] )

            if (sx!=0.0) or (sy!=0.0) or (sz!=0.0):
                print( "Do SetSamplePosition " )
                UGH.SetSamplePosition( sx, sy, sz )
                
        #self.ShowMessage( "st_Params=%s"%params )
        #hh.SetDetParam( "PSD,TRIGNET" )
        tmp_files = hh.MakeTempInfoFiles()
        return (tmp_files[0],tmp_files[1])

    #################################
    def GetHistogramParamsFromScript(self,filepath,_Ei,_HW_min,_HW_max,_HW_bin,_MaskFile):
        """
        """
        if not os.path.exists(filepath):
            return None
        modName = os.path.basename( filepath ).split(".")[0]
        dpath = os.path.dirname( filepath )
        sys.path.insert(0, dpath )
        TF = __import__( modName )
        attr_list = dir(TF)

        ret = {}
        ret[self.HSTKEY_HistParam] = (True,"hw,%f,%f,%f,%f"%( (_Ei,_HW_min,_HW_max,_HW_bin ) ) )
        ret[self.HSTKEY_DetParam]=(True,"PSD,TRIGNET")
        ret[self.HSTKEY_DetRange]=(False,"All")
        ret[self.HSTKEY_TimeRange]=(False,"All")
        ret[self.HSTKEY_FrameInfo]=(False,"None")
        ret[self.HSTKEY_MaskInfo]=(False,"NoFile")
        if _MaskFile!="":
            ret[self.HSTKEY_MaskInfo]=(True,_MaskFile)
        ret[self.HSTKEY_CaseInfo]=(False,"None")
        ret[self.HSTKEY_BGInfo]=(False,"TimeDep:None")
        ret[self.HSTKEY_TofShift]=(False,"None")
        ret[self.HSTKEY_AnaMode]=(False,"0,-,-")
        ret[self.HSTKEY_Options]=(False,"-")
        
        if self.HSTKEY_HistParam in attr_list:
            ret[self.HSTKEY_HistParam] = (True,TF.HistParam)
        if self.HSTKEY_DetParam in attr_list:
            ret[self.HSTKEY_DetParam] = (True,TF.DetParam)
        if self.HSTKEY_DetRange in attr_list:
            ret[self.HSTKEY_DetRange] = (True,TF.DetRange)
        if self.HSTKEY_DetRange in attr_list:
            ret[self.HSTKEY_DetRange] = (True,TF.DetRange)
        if self.HSTKEY_TimeRange in attr_list:
            ret[self.HSTKEY_TimeRange] = (True,TF.TimeRange)
        if self.HSTKEY_FrameInfo in attr_list:
            ret[self.HSTKEY_FrameInfo] = (True,TF.FrameInfo)
        if self.HSTKEY_MaskInfo in attr_list:
            ret[self.HSTKEY_MaskInfo] = (True,TF.MaskInfo)
        if self.HSTKEY_CaseInfo in attr_list:
            ret[self.HSTKEY_CaseInfo] = (True,TF.CaseInfo)
        if self.HSTKEY_BGInfo in attr_list:
            ret[self.HSTKEY_BGInfo] = (True,TF.BGInfo)
        if self.HSTKEY_TofShift in attr_list:
            ret[self.HSTKEY_TofShift] = (True,TF.TofShift)
        if self.HSTKEY_AnaMode in attr_list:
            ret[self.HSTKEY_AnaMode] = (True,TF.AnaMode)
        if self.HSTKEY_Options in attr_list:
            ret[self.HSTKEY_Options] = (True,TF.Options)

        return ret
        
    #################################
    def MakeCaseInfoFile(self,start_deg,end_deg,step_deg,runNo):
        """
        """
        print( "D4Mat2Utils::MakeTempInfoFiles" )
        
        fname = "CaseInfo_%s_%06d_%06d.xml" % (os.environ["USER"],runNo,os.getpid())
        if os.environ.has_key("UTSUSEMI_USR_PRIV_HOME"):
            ss = os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",fname)
        else:
            ss = os.path.join(os.environ["HOME"],"ana","xml",fname)
        
        template = '''<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE WiringInfo SYSTEM "CaseInfo.dtd" >
<caseInfo>
    <caseAmbiguity>1</caseAmbiguity>
    <filters/>
    <counters n="1">
    <counter i="0" type="ABP">
        <signal n="2">
            <trignet i="0" index="0" type="DIO" io="DIO1R" attr="A" title="A-Phase"/>
            <trignet i="1" index="0" type="DIO" io="DIO2R" attr="B" title="B-Phase"/>
        </signal>
        <conversionVal>0.002866242038</conversionVal>
'''
        template += '        <originVal unit="Degree">%f</originVal>\n'%(start_deg)
        template += '        <conditions type="2" >\n'
        template += '            <cond>%f,%f,%f</cond>\n'%(start_deg,end_deg,step_deg)
        template += '''
        </conditions>
    </counter>
    </counters>
</caseInfo>
'''
        fo = open( ss, "w" )
        fo.write( template )
        fo.close()
        
        return ss


#######################################
#  Plot2DMap
####################################### 
class Plot2DMap(object):
    """
    2次元マップ表示クラス
    """ 
    #########################################################
    def __init__(self, num, code, frame):
        """
        コンストラクタ
        @param  num  タブ No.
        @param  code  マップ画面タイトルに付する記号
        @param  frame  親フレーム
        @retval 無し
        """ 
        self.frame = frame
        self.code = code
        self.d2 = None
        if num == 0:
            self.ifi = UtilPlot.IFEvtProp(0)
            self.pno = 0  
        else:
            self.pno = (num+1) * 10  
            self.ifi = UtilPlot.IFEvtProp(self.pno) 

    #########################################
    def PlotMap(self, labels, eca, isRefresh=True):
        """
        2D マップ表示
        @param panel タブのインスタンス
        @param map　ElementContainerArray
        @retval 無し
        """
        d2m = M2P.D2Matrix()
        map = d2m.ReadMatrix( eca )
        
        # D2 プロッタが表示されているか
        if self.d2 == None:
            # 2Dプロッタフレームクローズイベントのリスナー登録
            self.ifi.AddListner('2dclosed',  self.OnNotify2DClose)
            self.d2 = D2Vis.MapD2Frame(self.frame , map, self.pno, self.code) 
        else:
            # データ変更
            if isRefresh:
                self.ifi.NotifyEvent(self, "changedata", map) 
            else:
                self.ifi.NotifyEvent(self, "updatedata", map) 

        self.ifi.NotifyEvent(self, "title", (labels[0], labels[1]))
        self.ifi.NotifyEvent(self, "scalelabel", (labels[2], labels[3], labels[4]))

        self.plotNow = (map, labels[0], labels[1])  
 
                
    #########################################
    def OnNotify2DClose(self, *args):
        """
        2Dプロッタクローズイベント受信処理
        @param evt　　イベント
        @retval 無し
        """
        self.d2 = None

    #########################################
    def Request2DClose(self):
        """
        2Dプロッタクローズ要求処理
        @param  無し
        @retval 無し
        """
         # 2Dプロッタが開いているなら
        if self.d2 == None:
             # 2Dプロッタのクローズ要求を出す　
            self.ifi.NotifyEvent(self, "close")

#######################################
#  Splash 
#######################################
class UtsusemiSplashScreen(wx.SplashScreen):
    def __init__(self,splash_path):

        bmp = wx.Image(splash_path).ConvertToBitmap()
        wx.SplashScreen.__init__(self,bmp,
                                 wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,
                                 5000, None, -1)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.fc = wx.FutureCall( 2000, self.ShowMain)

    def OnClose(self, evt):
        evt.Skip()
        self.Hide()
        if self.fc.IsRunning():
            self.fc.Stop()
            self.ShowMain()

    def ShowMain(self):
        pass


###############################
if __name__=='__main__':
    app = wx.App(False)
    
    #splash_path = os.path.join( os.environ["MLF_BASE_DIR"],"ana/Reduction/LOGO_utsusemi_s.png" )
    splash_path = os.path.join( os.environ["UTSUSEMI_BASE_DIR"],"ana","Reduction","LOGO_utsusemi_3_c_short.png" )
    if os.path.exists(splash_path):
        splash = UtsusemiSplashScreen(splash_path)
        splash.Show()
    
    frame = D4MatRSlicer(None)
    app.MainLoop()

        
