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

from __future__ import print_function
import utsusemi.vis.UtilQt as UtilQt
import uGao.uGaoUtil as UtilPlot
import uGao.M2PlotPlus as D2Vis
import Manyo.Utsusemi as mu
import Manyo.MLF as mmm
import utsusemi.ana.Reduction.BaseCommandsInEla as BC
import Manyo
import os
import sys
# import wx
# import wx.xrc as xrc

import time
import threading
import platform
if platform.python_version_tuple()[0] == '2':
    import thread as _thread
else:
    import _thread

USE_SLICEVIEW3D = False
try:
    import uGao.SliceViewer3D as SV
    USE_SLICEVIEW3D = True
except:
    pass

PYSIDEVER = 1
try:
    from PySide6 import QtCore, QtGui, QtWidgets
    from PySide6.QtGui import QAction
    PYSIDEVER = 6
except:
    try:
        from PySide2 import QtCore, QtGui, QtWidgets
        from PySide2.QtWidgets import QAction
        PYSIDEVER = 2
    except:
        from PySide import QtCore, QtGui
        import PySide.QtGui as QtWidgets
        from PySide.QtGui import QAction

try:
    import DR
except:
    pass

if mu.UtsusemiEnvGetDebugMode():
    mu.UtsusemiMessage("D4Mat2Slicer PySide Ver={}".format(PYSIDEVER))

if QtCore.__version__ < '5.0.0':
    from utsusemi.vis.ui_D4mat2SlicerQ import Ui_MainWindow, Ui_DataReductionPanel, Ui_XtalParamDialog
else:
    if PYSIDEVER == 2:
        from utsusemi.vis.ui2_D4mat2SlicerQ import Ui_MainWindow, Ui_DataReductionPanel, Ui_XtalParamDialog
    elif PYSIDEVER == 6:
        from utsusemi.vis.ui6_D4mat2SlicerQ import Ui_MainWindow, Ui_DataReductionPanel, Ui_XtalParamDialog

################################################
#                D4Mat2Slicer
#    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__ = 'ver15(20210305)'

DICT_TIMEINDEPBACK = {"SIK": "TOF:None", "DNA": "TOF:None", "AMR": "DARK:None"}
DICT_DETEFFI = {"SIK": "SIK-SUS304-3He-PSD.dat", "DNA": "None", "AMR": "None"}
INST_CODE = mu.UtsusemiEnvGetInstCode()
###############################################


def PutDefaultMaskFile(runNo):
    """
    """
    mask_file = ""
    AER = mu.UtsusemiAnaEnvironReader(mu.UTSUSEMIDEFAULTANAENVIRONFILE)
    # Get full path of parameter files
    p_files = AER.PutParamFiles(runNo, 0, True)
    if p_files.size() > 2:
        mask_file = p_files[2]
    del AER
    return mask_file

###############################################


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 = "default"
        self.NormFactor = 1000000.0
        self.TimeIndepBack = DICT_TIMEINDEPBACK[INST_CODE]
        self.DetEffi = DICT_DETEFFI[INST_CODE]
        self.GonioAtZero = 0.0
        self.Script = ""
        self.isInitial = True

################################################


class DataStoreContRot(object):
    def __init__(self):
        # self.RunNo = 0
        self.RunNoAngleList = [(0, 0.0)]  # list of (runNo, StartAngle)
        self.Ei = 0.0
        self.HW_bin = 0.0
        self.HW_min = 0.0
        self.HW_max = 0.0
        self.MaskFile = "default"
        self.NormFactor = 1000000.0
        self.TimeIndepBack = DICT_TIMEINDEPBACK[INST_CODE]
        self.DetEffi = DICT_DETEFFI[INST_CODE]
        # self.AngleStart = 0.0
        self.AngleMin = 0.0
        self.AngleMax = 0.0
        self.AngleStep = 0.0
        self.TimeSliceStart = -1
        self.TimeSliceEnd = -1
        self.Script = ""
        self.isInitial = True
        self.DeviceEncode = ""
        self.AngPerEncode = 0.0
        self.DeviceGonio = 0
        self.TrigNETinfoDIO = 1

###############################################


class TreatXmlParams(object):
    def __init__(self, parent):
        """
        """
        self.mode = 0
        # self.runNo=0
        self.runNoAngleList = [(0, 0.0)]
        self.ei = 0.0
        self.energyBin = 0.0
        self.energyMin = 0.0
        self.energyMax = 0.0
        self.maskFile = ""
        self.normFactor = 0.0
        self.timeIndepBack = DICT_TIMEINDEPBACK[INST_CODE]
        self.detEffi = DICT_DETEFFI[INST_CODE]
        # self.angleStart = 0.0
        self.angleMin = 0.0
        self.angleMax = 0.0
        self.angleStep = 0.0
        self.timeSlice0 = -1
        self.timeSlice1 = -1
        self.deviceEncode = ""
        self.anglePerEncode = 0.0
        self.dio = 0
        self.SBS_gonioAtZero = 0.0
        self.dataReductions = {"file": ""}
        self.main = parent
        if self.main.IsContinuousMethod:
            self.mode = 0

            if self.main.DataStoreContRot is not None:
                # self.runNo= self.main.DataStoreContRot.RunNo
                self.runNoAngleList = self.main.DataStoreContRot.RunNoAngleList[:]
                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.normFactor = self.main.DataStoreContRot.NormFactor
                self.timeIndepBack = self.main.DataStoreContRot.TimeIndepBack
                self.detEffi = self.main.DataStoreContRot.DetEffi
                self.angleMin = self.main.DataStoreContRot.AngleMin
                self.angleMax = self.main.DataStoreContRot.AngleMax
                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
                self.deviceEncode = self.main.DataStoreContRot.DeviceEncode
                self.anglePerEncode = self.main.DataStoreContRot.AngPerEncode
                self.dio = self.main.DataStoreContRot.TrigNETinfoDIO
        else:
            self.mode = 1

            if self.main.DataStoreStepByStep is not 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.normFactor = self.main.DataStoreStepByStep.NormFactor
                self.timeIndepBack = self.main.DataStoreStepByStep.TimeIndepBack
                self.detEffi = self.main.DataStoreStepByStep.DetEffi
                self.SBS_gonioAtZero = self.main.DataStoreStepByStep.GonioAtZero
                self.dataReductions["file"] = self.main.DataStoreStepByStep.Script

        if self.anglePerEncode == 0.0 and self.deviceEncode == "":
            inst_code = mu.UtsusemiEnvGetInstCode()
            XP = self.main.D4MatR.PutTreatD4Mat2XmlParams()
            if inst_code == "SIK":
                self.deviceEncode = "BL01-TL"
                #self.anglePerEncode = XP.deviceEncodeDic.Put(self.deviceEncode)
                self.anglePerEncode = XP.PutDeviceEncode(self.deviceEncode)
            elif inst_code == "AMR":
                self.deviceEncode = "BL14-TL"
                self.anglePerEncode = XP.PutDeviceEncode(self.deviceEncode)
        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_NORMFACT = "normFactor"
        self.KEY_TIMEBACK = "timeIndepBack"
        self.KEY_DETEFFI = "detectorEffiInfo"
        self.KEY_ANGS = "angleStart"
        self.KEY_ANGMIN = "angleMin"
        self.KEY_ANGMAX = "angleMax"
        self.KEY_ANGT = "angleStep"
        self.KEY_TSLS = "timeSlice"
        self.KEY_DEVENCODE = "deviceEncode"
        self.KEY_ANGPERENCODE = "anglePerEncode"
        self.KEY_DIO = "trignetDio"
        self.KEY_DRC = "dataReductions"
        self.KEY_DRC_F = 'file'
        self.KEY_SBS_GONIO = "SBSgonioAtZero"
        self.KEY_RUNLIST = 'runList'
        # self.KEY_RUNLIST_NUM = 'runList/num' #[inamura 230222] replaced
        # self.KEY_RUNLIST_RUN = 'runList/run'
        self.KEY_RUNLIST_NUM = 'num'
        self.KEY_RUNLIST_RUN = 'run'

    ################################
    def load(self, filename, isInitLoad=True):
        """
        Load XtalParam.xml

        @param filename (string) path to XtalParam.xml
        @param isInitLoad (bool) if loading file as initial parameter ( Executed marker is inisial )
        @retval True  : Succeeded to load file.
        @retval False : Failed.
        """
        runslist = []
        startAgnleList = []
        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) ))
                        runs = cnv.PutContent(pathtemp % (self.KEY_RUNNO))
                        if runs != "":
                            runss = runs.split(",")
                        else:
                            runss = ["0"]
                        runslist = []
                        for a_run in runss:
                            runslist.append(int(a_run))
                    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_NORMFACT)):
                        self.normFactor = float(cnv.PutContent(
                            pathtemp % (self.KEY_NORMFACT)))
                    if cnv.hasPath(pathtemp % (self.KEY_TIMEBACK)):
                        self.timeIndepBack = str(cnv.PutContent(
                            pathtemp % (self.KEY_TIMEBACK)))
                    if cnv.hasPath(pathtemp % (self.KEY_DETEFFI)):
                        self.detEffi = str(cnv.PutContent(
                            pathtemp % (self.KEY_DETEFFI)))
                    if cnv.hasPath(pathtemp % (self.KEY_ANGS)):
                        # self.angleStart= float(cnv.PutContent( pathtemp%(self.KEY_ANGS) ))
                        angs = cnv.PutContent(pathtemp % (self.KEY_ANGS))
                        if angs != "":
                            angss = angs.split(",")
                        else:
                            angss = ["0.0"]
                        startAngleList = []
                        for an_ang in angss:
                            startAngleList.append(float(an_ang))
                    if cnv.hasPath(pathtemp % (self.KEY_ANGMIN)):
                        self.angleMin = float(cnv.PutContent(
                            pathtemp % (self.KEY_ANGMIN)))
                    if cnv.hasPath(pathtemp % (self.KEY_ANGMAX)):
                        self.angleMax = float(cnv.PutContent(
                            pathtemp % (self.KEY_ANGMAX)))
                    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_DEVENCODE)):
                        self.deviceEncode = cnv.PutContent(pathtemp % (self.KEY_DEVENCODE))
                    if cnv.hasPath(pathtemp % (self.KEY_ANGPERENCODE)):
                        self.anglePerEncode = float(cnv.PutContent(pathtemp % (self.KEY_ANGPERENCODE)))
                    if cnv.hasPath(pathtemp % (self.KEY_DIO)):
                        self.dio = int(cnv.PutContent(
                            pathtemp % (self.KEY_DIO)))
                    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

                    if len(startAngleList) != len(runslist):
                        raise
                    else:
                        self.runNoAngleList = []
                        for a_run, startAngle in zip(runslist, startAngleList):
                            self.runNoAngleList.append((a_run, startAngle))

                    isOverWriteParams = True
                    if self.main.DataStoreContRot is None:
                        self.main.DataStoreContRot = DataStoreContRot()
                    if not self.main.DataStoreContRot.isInitial:
                        msg = "Already Data Reduction parameters are given. Do you overwrite these parameters ?"
                        ret = QtWidgets.QMessageBox().information(None, u"Warning", msg,
                                                                  QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.No)
                        if ret == QtWidgets.QMessageBox.Cancel:
                            isOverWriteParams = False

                    if self.anglePerEncode == 0.0 and self.deviceEncode == "":
                        inst_code = mu.UtsusemiEnvGetInstCode()
                        XP = self.main.D4MatR.PutTreatD4Mat2XmlParams()
                        if inst_code == "SIK":
                            self.deviceEncode = "BL01-TL"
                            #self.anglePerEncode = XP.deviceEncodeDic.Put(self.deviceEncode)
                            self.anglePerEncode = XP.PutDeviceEncode(self.deviceEncode)
                        elif inst_code == "AMR":
                            self.deviceEncode = "BL14-TL"
                            #self.anglePerEncode = XP.deviceEncodeDic.Put(self.deviceEncode)
                            self.anglePerEncode = XP.PutDeviceEncode(self.deviceEncode)

                    if isOverWriteParams:
                        # self.main.DataStoreContRot.RunNo = self.runNo
                        self.main.DataStoreContRot.RunNoAngleList = self.runNoAngleList[:]
                        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.NormFactor = self.normFactor
                        self.main.DataStoreContRot.TimeIndepBack = self.timeIndepBack
                        self.main.DataStoreContRot.DetEffi = self.detEffi
                        # self.main.DataStoreContRot.AngleStart = self.angleStart
                        self.main.DataStoreContRot.AngleMin = self.angleMin
                        self.main.DataStoreContRot.AngleMax = self.angleMax
                        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.DataStoreContRot.isInitial = False
                        self.main.DataStoreContRot.DeviceEncode = self.deviceEncode
                        self.main.DataStoreContRot.AngPerEncode = self.anglePerEncode
                        self.main.DataStoreContRot.TrigNETinfoDIO = self.dio

                    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_NORMFACT)):
                        self.normFactor = float(cnv.PutContent(
                            pathtemp % (self.KEY_NORMFACT)))
                    if cnv.hasPath(pathtemp % (self.KEY_TIMEBACK)):
                        self.timeIndepBack = str(cnv.PutContent(
                            pathtemp % (self.KEY_TIMEBACK)))
                    if cnv.hasPath(pathtemp % (self.KEY_DETEFFI)):
                        self.detEffi = str(cnv.PutContent(
                            pathtemp % (self.KEY_DETEFFI)))
                    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)):
                        key_runlist = self.KEY_RUNLIST
                        path_key = key_runlist + "/" + self.KEY_RUNLIST_NUM
                        # If Old version "runList/runList/num"
                        if not cnv.hasPath(pathtemp % (path_key)):
                            path_key = self.KEY_RUNLIST + "/" + self.KEY_RUNLIST + "/" + self.KEY_RUNLIST_NUM
                            if cnv.hasPath(pathtemp % (path_key)):
                                key_runlist = self.KEY_RUNLIST + "/" + self.KEY_RUNLIST
                                path_key = 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 ?"
                                ret = QtWidgets.QMessageBox().warning(None, u"Warning", msg,
                                                                      QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.No)
                                if ret == QtWidgets.QMessageBox.Cancel:
                                    isOverWriteParams = False
                            if isOverWriteParams:
                                # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                                self.main.RunList = {}
                                num_runs = int(cnv.PutContent(
                                    pathtemp % (path_key)))

                                for ind in range(num_runs):
                                    path_key = key_runlist + "/" + \
                                        self.KEY_RUNLIST_RUN + (",i=%d" % (ind))
                                    if cnv.hasPath(pathtemp % (path_key)):
                                        cont = cnv.PutContent(
                                            pathtemp % (path_key))
                                        # cont = "%s:%s:%08.3f:%g:%d"%(gonio_key, ex_runs, ex_angle,ex_protons, ex_mk)
                                        cl = cont.split(":")
                                        if len(cl) == 5:
                                            gonio_key = "%08.3f" % (
                                                float(cl[0]))
                                            if isInitLoad:
                                                mk_index = 1
                                            else:
                                                mk_index = int(cl[4])
                                            self.main.RunList[gonio_key] = (mk_index, cl[1], round(
                                                float(cl[2]), 3), round(float(cl[3]), 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 is None:
                        self.main.DataStoreStepByStep = DataStoreStepByStep()
                    if not self.main.DataStoreStepByStep.isInitial:
                        msg = "Already Data Reduction parameters are given. Do you overwrite these parameters ?"
                        ret = QtWidgets.QMessageBox().warning(None, u"Warning", msg,
                                                              QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.No)
                        if ret == QtWidgets.QMessageBox.Cancel:
                            isOverWriteParams = False

                    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.NormFactor = self.normFactor
                        self.main.DataStoreStepByStep.TimeIndepBack = self.timeIndepBack
                        self.main.DataStoreStepByStep.DetEffi = self.detEffi
                        self.main.DataStoreStepByStep.GonioAtZero = self.SBS_gonioAtZero
                        self.main.DataStoreStepByStep.Script = self.dataReductions[self.KEY_DRC_F]
                        self.main.DataStoreStepByStep.isInitial = False

                    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):
        ret_val = ""
        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"
                runNos = ""
                angleStarts = ""
                for a_run, an_angle in self.runNoAngleList:
                    runNos += "{:d},".format(a_run)
                    angleStarts += "{:g},".format(an_angle)
                if runNos != "":
                    runNos = runNos[:-1]
                    angleStarts = angleStarts[:-1]
                # ret = cnv.AddElement( pathtemp%(self.KEY_RUNNO), "%d"%self.runNo )
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_RUNNO), "%s" % runNos)
                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_NORMFACT), "%g" % self.normFactor)
                ret = cnv.AddElement(pathtemp % (
                    self.KEY_TIMEBACK), "%s" % self.timeIndepBack)
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_DETEFFI), "%s" % self.detEffi)
                # ret = cnv.AddElement( pathtemp%(self.KEY_ANGS), "%g"%self.angleStart )
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_ANGS), "%s" % angleStarts)
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_ANGMIN), "%g" % self.angleMin)
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_ANGMAX), "%g" % self.angleMax)
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_ANGT), "%g" % self.angleStep)
                ret = cnv.AddElement(pathtemp % (self.KEY_TSLS), "%f,%f" % (
                    self.timeSlice0, self.timeSlice1))
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_DEVENCODE), "%s" % (self.deviceEncode))
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_ANGPERENCODE), "%g" % (self.anglePerEncode))
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_DIO), "%d" % (self.dio))

                v_att = Manyo.MakeStringVector()
                v_val = Manyo.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_NORMFACT), "%g" % self.normFactor)
                ret = cnv.AddElement(pathtemp % (
                    self.KEY_TIMEBACK), "%s" % self.timeIndepBack)
                ret = cnv.AddElement(pathtemp %
                                     (self.KEY_DETEFFI), "%s" % self.detEffi)
                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 = ""
                    # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                    for gonio_key in self.main.RunList:
                        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)
                v_att = Manyo.MakeStringVector()
                v_val = Manyo.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):
                if cnv.isLoadXmlString():
                    ret_val = cnv.OutAllToString(True)
                else:
                    cnv.Save(str(filename))

        else:
            print("cannot open xml file %s" % (filename))
            return False

        del cnv
        if ret_val != "":
            return ret_val
        else:
            return True

#########################################
#       XtalParamTreatmentDialog
#########################################


class XtalParamTreatmentDialog(QtWidgets.QDialog):
    """
    Advanced treatment for XtalParam which enable to read and write partial information in XtalParam.
    """

    def __init__(self, parent):
        """
        Initialize
        @param parent
        @retval None
        """
        self.p = parent
        super(XtalParamTreatmentDialog, self).__init__(parent)
        self.frame = Ui_XtalParamDialog()
        if self.frame is None:
            return
        self.frame.setupUi(self)
        self.frame.btLoadXml.clicked.connect(self.OnLoadFile)
        self.frame.btSaveXml.clicked.connect(self.OnSaveFile)

        self.frame.rd_AllParams.clicked.connect(self.OnToggleAll)
        self.frame.rd_PartialParam.clicked.connect(self.OnTogglePartial)

        self.frame.rd_PartialParam.setChecked(True)
        self.frame.cb_LC.setChecked(False)
        self.frame.cb_OR.setChecked(False)
        self.frame.cb_PR.setChecked(False)
        self.frame.cb_SL.setChecked(False)
        self.frame.cb_DF.setChecked(False)
        self.frame.cb_DR.setChecked(False)
        self.OnToggle()
        self.show()

    ##########################################################

    def OnLoadFile(self):
        """
        Load partial Xtalparam information from a file with the condition given by radio buttons
        @param None
        @retval None
        """
        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u"Open XtalParam file ...", os.getcwd(), filter="xml (*.xml)")
        if filepath == "":
            return
        filepath = str(filepath)
        flags, DRflag = self.CheckAll()
        self.p.OnLoadXtalParam(
            evt=None, input_xml=filepath, flags=flags, DRflag=DRflag)
        self.close()
        return

    ##########################################################
    def OnSaveFile(self):
        """
        Save partial Xtalparam information as a file with the condition given by radio buttons
        @param None
        @retval None
        """
        filepath, filt = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save XtalParam file ...", os.path.join(os.getcwd(), "XtalParam.xml"), filter='xml (*.xml)')
        if filepath == "":
            return
        filepath = str(filepath)
        flags, DRflag = self.CheckAll()
        self.p.OnSaveXtalParam(evt=None, toFile=True,
                               filepath=filepath, flags=flags, DRflag=DRflag)
        self.close()
        return

    ##########################################################
    def OnToggle(self):
        """
        Change enabled status for each radio button
        @param None
        @retval None
        """
        flag = bool(self.frame.rd_PartialParam.isChecked())
        self.frame.cb_LC.setEnabled(flag)
        self.frame.cb_OR.setEnabled(flag)
        self.frame.cb_PR.setEnabled(flag)
        self.frame.cb_SL.setEnabled(flag)
        self.frame.cb_DF.setEnabled(flag)
        self.frame.cb_DR.setEnabled(flag)
        return

    ##########################################################
    def OnToggleAll(self):
        """
        Change enabled status for each radio button
        @param None
        @retval None
        """
        flag = not bool(self.frame.rd_AllParams.isChecked())
        self.frame.rd_PartialParam.setChecked(flag)
        self.OnToggle()

    ##########################################################
    def OnTogglePartial(self):
        """
        Change enabled status for each radio button
        @param None
        @retval None
        """
        flag = not bool(self.frame.rd_PartialParam.isChecked())
        self.frame.rd_AllParams.setChecked(flag)
        self.OnToggle()

    ##########################################################
    def CheckAll(self):
        """
        Check all status of radio buttons
        @param None
        @retval tupple of flags ( flags for UtsusemiSqeCalcXtalParam and DataReduction for D4Mat2Slicer )
        """
        XP = mu.UtsusemiSqeCalcXtalParams()
        flags = 0
        if self.frame.cb_LC.isChecked():
            flags += XP.TOXML_LATTICECONST
        if self.frame.cb_OR.isChecked():
            flags += XP.TOXML_ORIENTATION
        if self.frame.cb_PR.isChecked():
            flags += XP.TOXML_PROJECTION
        if self.frame.cb_SL.isChecked():
            flags += XP.TOXML_SLICINGINFO
        if self.frame.cb_DF.isChecked():
            flags += XP.TOXML_DIAGONALFOLD

        if flags == 0:
            flags = None

        if self.frame.cb_DR.isChecked():
            DRflag = True
        else:
            DRflag = False

        return (flags, DRflag)


#########################################
#       SetTemperatureNxSPEDialog
#########################################
class SetTemperatureNxSPEDialog(QtWidgets.QDialog):
    """
    Temperature of NxSPE 設定ダイアログクラス
    """
    ##########################################################

    def __init__(self, parent):
        """
        コンストラクタ
        @param  parent   親ウィンドウのID
        @retval 無し
        """
        super(SetTemperatureNxSPEDialog, self).__init__(parent)
        self.setWindowTitle("Set Temperature to NxSPE")
        btns = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)
        btns.accepted.connect(self.accept)
        btns.rejected.connect(self.reject)
        gl = QtWidgets.QGridLayout()
        gl.addWidget(QtWidgets.QLabel("Set temperature of sample"))
        self.lineedit = QtWidgets.QLineEdit("300.0")
        gl.addWidget(self.lineedit)
        gl.addWidget(btns)
        self.setLayout(gl)

    def get_temp(self):
        try:
            temp = float(self.lineedit.text())
        except:
            temp = 0.0
        return temp

    @staticmethod
    def get_temperature(parent=None):
        dialog = SetTemperatureNxSPEDialog(parent)
        if PYSIDEVER == 6:
            result = dialog.exec()
        else:
            result = dialog.exec_()
        temp = dialog.get_temp()
        return (temp, result == QtWidgets.QDialog.Accepted)

###############################################


class DataReductionPanel(QtWidgets.QMainWindow):
    def __init__(self, parent, mainpanel):
        """
        """
        self.parent = parent
        self.main = mainpanel
        # Make window and set Event handler
        super(DataReductionPanel, self).__init__(None)
        self.frame = Ui_DataReductionPanel()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        self.btDoReduction = self.findChild(
            QtWidgets.QPushButton, u'btDoReduction')
        self.btDoReduction.clicked.connect(self.OnReduction)
        self.StepByStepButton = self.findChild(
            QtWidgets.QPushButton, u"btLoadRunInfoFile")
        self.StepByStepButton.clicked.connect(self.OnLoadRunInfoFile)
        self.StepByStepButton2 = self.findChild(
            QtWidgets.QPushButton, u"btSbSAdd")
        self.StepByStepButton2.clicked.connect(self.OnAddStepByStepRun)
        self.StepByStepClear = self.findChild(
            QtWidgets.QPushButton, u"btClearRunInfo")
        self.StepByStepClear.clicked.connect(self.OnClearRunInfo)
        self.StepByStepCalc = self.findChild(
            QtWidgets.QPushButton, u"btReCalc")
        self.StepByStepCalc.clicked.connect(self.OnReCalcAngle)
        # self.btLoadXtalParam2 = self.findChild(QtWidgets.QPushButton,u"btLoadXtalParam2" )
        # self.btLoadXtalParam2.clicked.connect(self.OnLoadXtalParam)
        # self.btSaveXtalParam2 = self.findChild(QtWidgets.QPushButton,u"btSaveXtalParam2" )
        # self.btSaveXtalParam2.clicked.connect(self.OnSaveXtalParam)
        self.btSelectMaskFile = self.findChild(
            QtWidgets.QPushButton, u"btSelectMaskFile")
        self.btSelectMaskFile.clicked.connect(self.OnSelectMaskFile)

        # Radio Button control for measurement method
        self.rbContRotMethod = self.findChild(
            QtWidgets.QRadioButton, u'rbContRotMethod')
        self.rbContRotMethod.clicked.connect(self.OnTurnRadioButtonForMethod)
        self.rbStepByStepMethod = self.findChild(
            QtWidgets.QRadioButton, u'rbStepByStepMethod')
        self.rbStepByStepMethod.clicked.connect(
            self.OnTurnRadioButtonForMethod)
        self.RadioButtonList = []
        self.RadioButtonList.append(self.rbContRotMethod)
        self.RadioButtonList.append(self.rbStepByStepMethod)

        # Radio Button control for data reduction script
        self.rbUseDRDefault = self.findChild(
            QtWidgets.QRadioButton, u'rbUseDRDefault')
        self.rbUseDRDefault.clicked.connect(self.OnTurnRadioButtonForDR)
        self.rbUseDRScript = self.findChild(
            QtWidgets.QRadioButton, u'rbUseDRScript')
        self.rbUseDRScript.clicked.connect(self.OnTurnRadioButtonForDR)
        self.RadioButtonListForDR = []
        self.RadioButtonListForDR.append(self.rbUseDRDefault)
        self.RadioButtonListForDR.append(self.rbUseDRScript)
        self.isUseDRScript = False
        self.DRScriptSelectButton = self.findChild(
            QtWidgets.QPushButton, u"btSelectDRScript")
        self.DRScriptSelectButton.clicked.connect(self.OnSelectDRScript)
        self.DRScriptTempButton = self.findChild(
            QtWidgets.QPushButton, u"btMakeDRTemp")
        self.DRScriptTempButton.clicked.connect(self.OnMakeDRScriptTemp)
        self.DRScriptPathLabel = self.findChild(
            QtWidgets.QLabel, u"lbDRScriptPath")
        self.DRScriptPath = "Not Selected"

        # Button control
        self.ButtonCtrlList = []
        self.ButtonCtrlList.append(self.btDoReduction)

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(True)

        # Continuous Reduction Params bind
        self.PanelContRot = self.findChild(
            QtWidgets.QGroupBox, u"gbContRotMethod")
        self.ContRedParams = [None, None, None, None, None, None, None, None, None, None]
        self.ContRedParams[0] = self.findChild(
            QtWidgets.QLineEdit, u"txtRunNo")
        self.ContRedParams[1] = self.findChild(
            QtWidgets.QLineEdit, u"txtStartDeg")
        self.ContRedParams[2] = self.findChild(
            QtWidgets.QLineEdit, u"txtMinDeg")
        self.ContRedParams[3] = self.findChild(
            QtWidgets.QLineEdit, u"txtMaxDeg")
        self.ContRedParams[4] = self.findChild(
            QtWidgets.QLineEdit, u"txtStepDeg")
        self.ContRedParams[5] = self.findChild(
            QtWidgets.QLineEdit, u"txtTimeSliceStart")
        self.ContRedParams[6] = self.findChild(
            QtWidgets.QLineEdit, u"txtTimeSliceEnd")
        self.ContRedParams[7] = self.findChild(
            QtWidgets.QComboBox, u"cbAngPerEncode")
        self.ContRedParams[8] = self.findChild(
            QtWidgets.QLineEdit, u"txtAngPerEncode")
        self.ContRedParams[9] = self.findChild(
            QtWidgets.QComboBox, u"cbTrigNETinfoIO")
        self.ContRedParams[7].currentIndexChanged.connect(self.OnChangedAngPerEncode)

        self.findChild(QtWidgets.QLineEdit,
                       u"txtTrigNETdaqId").setEnabled(False)
        self.findChild(QtWidgets.QLineEdit,
                       u"txtTrigNETmodNo").setEnabled(False)

        # Step by Step Param bind
        self.PanelStepByStep = self.findChild(
            QtWidgets.QGroupBox, u"gbStepByStepMethod")
        self.StepByStepParams = [None, None, None, None]
        self.StepByStepParams[0] = self.findChild(
            QtWidgets.QLineEdit, u"txtOrgAngle")
        self.StepByStepParams[1] = self.findChild(
            QtWidgets.QLineEdit, u"txtSbSRunNo")
        self.StepByStepParams[2] = self.findChild(
            QtWidgets.QLineEdit, u"txtSbSAngle")
        self.StepByStepParams[3] = self.findChild(
            QtWidgets.QLineEdit, u"txtSbSProtons")

        # Reduction Params bind
        self.ReductionParams = [None, None, None, None, None, None, None, None]
        self.ReductionParams[0] = self.findChild(QtWidgets.QLineEdit, u"txtEi")
        self.ReductionParams[1] = self.findChild(
            QtWidgets.QLineEdit, u"txtEnergyBin")
        self.ReductionParams[2] = self.findChild(
            QtWidgets.QLineEdit, u"txtEnergyMin")
        self.ReductionParams[3] = self.findChild(
            QtWidgets.QLineEdit, u"txtEnergyMax")
        self.ReductionParams[4] = self.findChild(
            QtWidgets.QLineEdit, u"txMaskFilePath")
        self.ReductionParams[5] = self.findChild(
            QtWidgets.QLineEdit, u"txtNormFactor")
        self.ReductionParams[6] = self.findChild(
            QtWidgets.QLineEdit, u"txtTimeIndepBack")
        self.ReductionParams[7] = self.findChild(
            QtWidgets.QLineEdit, u"txtDetEffi")

        # Run List
        self.lstRunInfo = self.findChild(
            QtWidgets.QTreeWidget, u'lstRunStepInfo')
        self.lstRunInfo.setSelectionMode(
            QtWidgets.QAbstractItemView.ExtendedSelection)
        self.statusImage = [None, None, None, None, None]
        self.statusImage[0] = UtilQt.ImagesXpm().GetQPixmap("Red")
        self.statusImage[1] = UtilQt.ImagesXpm().GetQPixmap("Green")
        self.statusImage[2] = UtilQt.ImagesXpm().GetQPixmap("Processing")
        self.statusImage[3] = UtilQt.ImagesXpm().GetQPixmap("GreenEnd")
        self.statusImage[4] = UtilQt.ImagesXpm().GetQPixmap("RedEnd")

        self.lstRunInfo.setColumnCount(2)
        self.lstRunInfo.setHeaderLabels(["Angle", "RunNo"])
        self.lstRunInfo.setColumnWidth(0, 110)
        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.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].setChecked(True)
            self.RadioButtonList[1].setChecked(False)
            self.OnTurnRadioButtonForMethod(self.main.IsContinuousMethod)
            self.PanelContRot.setEnabled(True)
            self.PanelStepByStep.setEnabled(False)
            if self.main.DataStoreContRot is not None:
                self.ReductionParams[0].setText(
                    "%g" % (self.main.DataStoreContRot.Ei))
                self.ReductionParams[1].setText(
                    "%g" % (self.main.DataStoreContRot.HW_bin))
                self.ReductionParams[2].setText(
                    "%g" % (self.main.DataStoreContRot.HW_min))
                self.ReductionParams[3].setText(
                    "%g" % (self.main.DataStoreContRot.HW_max))
                self.ReductionParams[4].setText(
                    "%s" % (self.main.DataStoreContRot.MaskFile))
                self.ReductionParams[5].setText(
                    "%g" % (self.main.DataStoreContRot.NormFactor))
                self.ReductionParams[6].setText(
                    "%s" % (self.main.DataStoreContRot.TimeIndepBack))
                self.ReductionParams[7].setText(
                    "%s" % (self.main.DataStoreContRot.DetEffi))
                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.setText(
                            basename_script + "(Current Dir)")
                    else:
                        self.DRScriptPathLabel.setText(
                            basename_script + "(%s)" % (dirname_script))
                    self.OnTurnRadioButtonForDR(False)
                else:
                    self.OnTurnRadioButtonForDR(True)
                runNos = ""
                angleStarts = ""
                for a_run, an_angle in self.main.DataStoreContRot.RunNoAngleList:
                    runNos += "{:d},".format(a_run)
                    angleStarts += "{:g},".format(an_angle)
                if runNos != "":
                    runNos = runNos[:-1]
                    angleStarts = angleStarts[:-1]
                self.ContRedParams[0].setText("%s" % (runNos))
                self.ContRedParams[1].setText("%s" % (angleStarts))
                # self.ContRedParams[0].setText("%d"%(self.main.DataStoreContRot.RunNo))
                # self.ContRedParams[1].setText("%g"%(self.main.DataStoreContRot.AngleStart))
                self.ContRedParams[2].setText(
                    "%g" % (self.main.DataStoreContRot.AngleMin))
                self.ContRedParams[3].setText(
                    "%g" % (self.main.DataStoreContRot.AngleMax))
                self.ContRedParams[4].setText(
                    "%g" % (self.main.DataStoreContRot.AngleStep))
                self.ContRedParams[5].setText(
                    "%g" % (self.main.DataStoreContRot.TimeSliceStart))
                self.ContRedParams[6].setText(
                    "%g" % (self.main.DataStoreContRot.TimeSliceEnd))
                if self.main.DataStoreContRot.DeviceEncode == "BL01-TL":
                    ind = 0
                elif self.main.DataStoreContRot.DeviceEncode == "BL14-TL":
                    ind = 1
                else:
                    ind = 2  # other val
                self.ContRedParams[7].setCurrentIndex(ind)
                self.ContRedParams[8].setText(
                    "%g" % (self.main.DataStoreContRot.AngPerEncode))
                self.OnChangedAngPerEncode()
                self.ContRedParams[9].setCurrentIndex(
                    self.main.DataStoreContRot.TrigNETinfoDIO - 1)
        else:
            self.RadioButtonList[0].setChecked(False)
            self.RadioButtonList[1].setChecked(True)
            self.OnTurnRadioButtonForMethod(self.main.IsContinuousMethod)
            self.PanelContRot.setEnabled(False)
            self.PanelStepByStep.setEnabled(True)
            if self.main.DataStoreStepByStep is not None:
                self.ReductionParams[0].setText(
                    "%g" % (self.main.DataStoreStepByStep.Ei))
                self.ReductionParams[1].setText(
                    "%g" % (self.main.DataStoreStepByStep.HW_bin))
                self.ReductionParams[2].setText(
                    "%g" % (self.main.DataStoreStepByStep.HW_min))
                self.ReductionParams[3].setText(
                    "%g" % (self.main.DataStoreStepByStep.HW_max))
                self.ReductionParams[4].setText(
                    "%s" % (self.main.DataStoreStepByStep.MaskFile))
                self.ReductionParams[5].setText(
                    "%g" % (self.main.DataStoreStepByStep.NormFactor))
                self.ReductionParams[6].setText(
                    "%s" % (self.main.DataStoreStepByStep.TimeIndepBack))
                self.ReductionParams[7].setText(
                    "%s" % (self.main.DataStoreStepByStep.DetEffi))
                self.StepByStepParams[0].setText(
                    "%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.setText(
                            os.path.basename(self.DRScriptPath))
                    else:
                        self.DRScriptPathLabel.setText(self.DRScriptPath)
                    self.OnTurnRadioButtonForDR(False)
                else:
                    self.OnTurnRadioButtonForDR(True)
            # self.lstRunInfo.DeleteAllItems()
            self.lstRunInfo.clear()
            for i in range(len(self.main.RunList)):
                found_key = ""
                # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                for gonio_key in self.main.RunList:
                    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]
                new_line = QtWidgets.QTreeWidgetItem()
                new_line.setText(0, "%8.3f" % (ex_angle))
                new_line.setIcon(0, self.statusImage[ex_mk])
                new_line.setText(1, ex_runs)
                self.lstRunInfo.addTopLevelItem(new_line)

    #################################
    def OnTurnRadioButtonForMethod(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] onTurnRadioButton")
        bt = self.sender()
        if bt is None:
            if evt:
                bt = self.RadioButtonList[0]
            else:
                bt = self.RadioButtonList[1]

        if (bt == self.RadioButtonList[0]):
            self.main.ShowMessage("[DRPanel] --- Continuous Rotation Method")
            self.main.IsContinuousMethod = True
            self.main.OnLineModeBox.setEnabled(True)

        elif (bt == self.RadioButtonList[1]):
            self.main.ShowMessage("[DRPanel] --- Step By Step Method")
            self.main.IsContinuousMethod = False
            self.main.OnLineModeBox.setEnabled(False)
        if self.main.D4MatR.Empty():
            self.main.BtnDRExec.setEnabled(False)
        self.ChangeStatusOfParts()

    #################################
    def OnTurnRadioButtonForDR(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] onTurnRadioButtonForDR")
        bt = self.sender()
        if bt is None:
            if evt:
                bt = self.RadioButtonListForDR[0]
                self.RadioButtonListForDR[0].setChecked(True)
                self.RadioButtonListForDR[1].setChecked(False)
            else:
                bt = self.RadioButtonListForDR[1]
                self.RadioButtonListForDR[0].setChecked(False)
                self.RadioButtonListForDR[1].setChecked(True)

        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.setEnabled(self.isUseDRScript)
        self.DRScriptTempButton.setEnabled(self.isUseDRScript)
        self.DRScriptPathLabel.setEnabled(self.isUseDRScript)
        if self.main.IsContinuousMethod:
            self.PanelContRot.setEnabled(True)
            self.PanelStepByStep.setEnabled(False)
        else:
            self.PanelContRot.setEnabled(False)
            self.PanelStepByStep.setEnabled(True)

    #################################
    def OnChangedAngPerEncode(self, evt=None):
        """
        """
        XP = self.D4MatR.PutTreatD4Mat2XmlParams()
        conv = self.ContRedParams[7].currentIndex()
        if conv == 0:  # BL01-TL
            self.ContRedParams[8].setEnabled(False)
            #self.ContRedParams[8].setText("{:g}".format(XP.deviceEncodeDic.Put("BL01-TL")))
            self.ContRedParams[8].setText("{:g}".format(XP.PutDeviceEncode("BL01-TL")))
        elif conv == 1:  # BL14-TL
            self.ContRedParams[8].setEnabled(False)
            #self.ContRedParams[8].setText("{:g}".format(XP.deviceEncodeDic.Put("BL14-TL")))
            self.ContRedParams[8].setText("{:g}".format(XP.PutDeviceEncode("BL14-TL")))
        else:
            self.ContRedParams[8].setEnabled(True)
            self.ContRedParams[8].setText("{:g}".format(self.main.DataStoreContRot.AngPerEncode))

    #################################
    def OnReduction(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] OnReduction")
        isForced = False
        if type(evt) == bool:
            isForced = evt

        Ei = float(self.ReductionParams[0].text().strip())
        dhw = float(self.ReductionParams[1].text().strip())
        hw_min = float(self.ReductionParams[2].text().strip())
        hw_max = float(self.ReductionParams[3].text().strip())
        mask_file = str(self.ReductionParams[4].text().strip())
        norm_factor = float(self.ReductionParams[5].text())
        time_indep_back = str(self.ReductionParams[6].text())
        det_effi = str(self.ReductionParams[7].text())
        # Check given energy parameters
        if (not isForced) and (hw_max >= Ei or hw_min > hw_max or dhw <= 0.0):
            msg = "Invalid Energy Parameter."
            dlg = QtWidgets.QMessageBox().critical(
                None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)
            return
        # Check mask information
        if mask_file == "" or mask_file.upper() == "NONE":
            mask_file = ""
        elif mask_file.upper() == "DEFAULT":
            mask_file = "default"
        elif mu.FindParamFilePath(mask_file) == "":
            msg = "Mask File is not found."
            dlg = QtWidgets.QMessageBox().critical(
                None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)
            return
        # Check given script
        if self.DRScriptPathLabel.isEnabled():
            print("---- self.DRScriptPath = ", self.DRScriptPath)
            if not self.CheckDRScript(self.DRScriptPath):
                msg = "Failed to import Script File."
                dlg = QtWidgets.QMessageBox().critical(
                    None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)
                return
            else:
                DR_script = self.DRScriptPath
        else:
            DR_script = ""

        if (self.main.IsContinuousMethod):
            # if Continuout rotation method
            # runNo  = int( self.ContRedParams[0].text().strip() )
            # st_deg = float( self.ContRedParams[1].text().strip() )
            runNo = self.ContRedParams[0].text().strip()
            st_deg = self.ContRedParams[1].text().strip()
            min_deg = float(self.ContRedParams[2].text().strip())
            max_deg = float(self.ContRedParams[3].text().strip())
            w_deg = float(self.ContRedParams[4].text().strip())
            t_start = float(self.ContRedParams[5].text().strip())
            t_end = float(self.ContRedParams[6].text().strip())
            dev_ang_per_enc = self.ContRedParams[7].currentText()
            #if self.D4MatR.PutTreatD4Mat2XmlParams().deviceEncodeDic.Check(dev_ang_per_enc) == 0:
            if self.D4MatR.PutTreatD4Mat2XmlParams().CheckDeviceEncodeName(dev_ang_per_enc) == 0:
                dev_ang_per_enc = ""
            val_ang_per_enc = float(self.ContRedParams[8].text())
            dio = int(self.ContRedParams[9].currentIndex() + 1)

            if not isForced:
                # Estimate the mount of memory required for data reduction
                inst_code = mu.UtsusemiEnvGetInstCode()
                if inst_code == "SIK":
                    N = 352 * 100  # PSD * Pixel
                elif inst_code == "AMR":
                    N = 290 * 120
                else:
                    N = 350 * 100
                M_GB = 45.2 * float(N) * ((hw_max - hw_min) / dhw * (max_deg - min_deg) / w_deg) / 1024.0 / 1024.0 / 1024.0 + 7.20
                msg = "This data reduction requires memory of about {:.1f} GB.".format(
                    M_GB)
                ret = QtWidgets.QMessageBox().warning(None, u"Warning", msg,
                                                      QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
                if ret == QtWidgets.QMessageBox.Cancel:
                    return

            if self.main.DataStoreContRot is None:
                self.main.DataStoreContRot = DataStoreContRot()
            """
            else:
                ## If all parameters are same as previous ones, do nothing
                if (not isForced) and (self.main.DataStoreContRot.RunNo==runNo) \
                   and (self.main.DataStoreContRot.Ei==Ei) and (self.main.DataStoreContRot.HW_bin==dhw) \
                   and (self.main.DataStoreContRot.HW_min==hw_min) and (self.main.DataStoreContRot.HW_max==hw_max) \
                   and (self.main.DataStoreContRot.AngleStart==st_deg) and (self.main.DataStoreContRot.AngleMin==min_deg) \
                   and (self.main.DataStoreContRot.AngleMax==max_deg) and (self.main.DataStoreContRot.AngleStep==w_deg) \
                   and (self.main.DataStoreContRot.TimeSliceStart==t_start) and (self.main.DataStoreContRot.TimeSliceEnd==t_end) \
                   and (self.main.DataStoreContRot.TrigNETinfoDIO==dio) and (self.main.DataStoreContRot.MaskFile==mask_file) \
                   and (self.main.DataStoreContRot.NormFactor==norm_factor) and (self.main.DataStoreContRot.TimeIndepBack==time_indep_back) \
                   and (self.main.DataStoreContRot.DetEffi==det_effi)and (self.main.DataStoreContRot.Script==DR_script):
                    return
            """
            # self.main.DataStoreContRot.RunNo = runNo
            runNos = runNo.split(",")
            st_degs = st_deg.split(",")
            runNoAngles = []
            if len(runNos) != len(st_degs):
                msg = "The number of Start Angle must be same as that of RunNo"
                dlg = QtWidgets.QMessageBox().critical(
                    None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)
                return
            for a_run, a_deg in zip(runNos, st_degs):
                runNoAngles.append((int(a_run), float(a_deg)))
            self.main.DataStoreContRot.RunNoAngleList = runNoAngles[:]
            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.AngleMin = min_deg
            self.main.DataStoreContRot.AngleMax = max_deg
            self.main.DataStoreContRot.AngleStep = w_deg
            self.main.DataStoreContRot.TimeSliceStart = t_start
            self.main.DataStoreContRot.TimeSliceEnd = t_end
            self.main.DataStoreContRot.DeviceEncode = dev_ang_per_enc
            self.main.DataStoreContRot.AngPerEncode = val_ang_per_enc
            self.main.DataStoreContRot.TrigNETinfoDIO = dio
            self.main.DataStoreContRot.MaskFile = mask_file
            self.main.DataStoreContRot.NormFactor = norm_factor
            self.main.DataStoreContRot.TimeIndepBack = time_indep_back
            self.main.DataStoreContRot.DetEffi = det_effi
            self.main.DataStoreContRot.Script = DR_script
            self.main.DataStoreContRot.isInitial = False
            self.main.doneOnLineModeFirstPrmSet = False
            # if runNo==0:
            if runNoAngles[0][0] == 0:
                runNo_st = "None [ Virtual ]"
            else:
                # runNo_st = "%06d [ continuous ]"%(runNo)
                runNo_st = runNo
            exp_info = "Ei=%g (meV) / Rot= %.3g:%.3g:%.3g (deg.)" % (Ei,
                                                                     min_deg, w_deg, max_deg)
        else:
            min_runNo = 1000000
            max_runNo = -1
            min_ang = 360.0
            max_ang = -360.0
            isAfterDR = False
            # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
            for gonio_key in self.main.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                if ex_mk > 1:
                    isAfterDR = True
                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 [StepByStep]" % (min_runNo, max_runNo)
            exp_info = "Ei=%g (meV)\nAng= %s : %s" % (Ei, min_ang, max_ang)
            try:
                gonio_atZero = float(self.StepByStepParams[0].text().strip())
            except:
                gonio_atZero = 0.0

            if self.main.DataStoreStepByStep is None:
                self.main.DataStoreStepByStep = DataStoreStepByStep()
            else:
                # If all parameters are same as previous ones, do nothing
                if (isAfterDR) and (not isForced) and (self.main.DataStoreStepByStep.Ei == Ei) and (self.main.DataStoreStepByStep.HW_bin == dhw) and \
                   (self.main.DataStoreStepByStep.HW_min == hw_min) and (self.main.DataStoreStepByStep.HW_max == hw_max) and \
                   (self.main.DataStoreStepByStep.MaskFile == mask_file) and (self.main.DataStoreStepByStep.GonioAtZero == gonio_atZero) and \
                   (self.main.DataStoreStepByStep.NormFactor == norm_factor) and (self.main.DataStoreStepByStep.TimeIndepBack == time_indep_back) and \
                   (self.main.DataStoreStepByStep.DetEffi == det_effi) and (self.main.DataStoreStepByStep.Script == DR_script):
                    self.main.txtRunNo.setText(runNo_st)
                    self.main.txtExpInfo.setText(exp_info)
                    return

            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.NormFactor = norm_factor
            self.main.DataStoreStepByStep.TimeIndepBack = time_indep_back
            self.main.DataStoreStepByStep.DetEffi = det_effi
            self.main.DataStoreStepByStep.GonioAtZero = gonio_atZero
            self.main.DataStoreStepByStep.Script = DR_script

        if (not isForced) and (not self.main.D4MatR.Empty()):
            # Confirmation to clear previous D4Mat2 data
            msg = "Some parameters were changed. Do you want to DELETE privious D4Mat2 data ?"
            ret = QtWidgets.QMessageBox().warning(None, u"WARNING", msg,
                                                  QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
            if ret == QtWidgets.QMessageBox.No:
                return
            else:
                if self.main.IsContinuousMethod:
                    pass
                else:
                    # clear marks for runNos for data reduction
                    # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                    for gonio_key in self.main.RunList:
                        ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                        self.main.RunList[gonio_key] = (
                            1, ex_runs, ex_angle, ex_protons, ex_ind)
                        self.lstRunInfo.topLevelItem(
                            ex_ind).setIcon(0, self.statusImage[1])
                # Delete D4Mat2 data
                self.main.D4MatR.ResetD4mat()
                # Update buttons conditions on MainPanel
                self.main.IsReadyProjection = False
                self.main.isEnableSlice = False
                self.main.ButtonCtrlAfterDR(False)
                self.main.CheckEnableSliceButton()

        # Set to UtsusemiD4Matrix2
        if self.main.IsContinuousMethod:
            self.D4MatR.SetD4MatMode(0)
        else:
            self.D4MatR.SetD4MatMode(1)
            self.D4MatR.SetD4MatDataReductionStepByStepGonioAtZero(gonio_atZero)
            for a_key in self.main.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[a_key]
                self.D4MatR.SetD4MatDataReductionStepByStepAddRunAngles(ex_runs, ex_angle, ex_protons, norm_factor)

        self.main.D4MatR.SetD4MatDataReductionOptions(mask_file, norm_factor, time_indep_back, det_effi, DR_script)

        if not isForced:
            self.main.BtnDRExec.setEnabled(True)
            self.main.txtRunNo.setText(runNo_st)
            self.main.txtExpInfo.setText(exp_info)
            self.main.OnLineModeBtn.setEnabled(self.main.IsContinuousMethod)

    #################################
    def OnClearRunInfo(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] OnClearRunInfo")
        sellist = self.lstRunInfo.selectedItems()
        # if some items are selected
        if len(sellist) > 0:
            sel_index_list = []
            # take out indices of selected items
            for i in sellist:
                sel_index_list.append(self.lstRunInfo.indexOfTopLevelItem(i))
            sel_index_list.sort()
            index_list = []
            # item indices larger then removed index are shifted (decreased)
            for index in sel_index_list:
                pre_size = len(index_list)
                index_list.append(index - pre_size)
            for index in index_list:
                # delete information
                for gonio_key in self.main.RunList:
                    ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                    if ex_ind == index:
                        del self.main.RunList[gonio_key]
                        break
                # reset indices below removed item
                for gonio_key in self.main.RunList:
                    ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                    if ex_ind > index:
                        self.main.RunList[gonio_key] = (
                            ex_mk, ex_runs, ex_angle, ex_protons, (ex_ind - 1))
                self.lstRunInfo.takeTopLevelItem(index)
            return
        self.lstRunInfo.clear()
        self.main.RunList = {}
        self.main.D4MatR.ClearAll()

    #################################
    def OnClose(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] OnClose")
        self.close()

    #################################
    def OnLoadRunInfoFile(self, evt=None):
        """
        """
        self.main.ShowMessage("[DRPanel] OnLoadRunInfoFile")

        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u"Open RunInfo file ...", os.getcwd(), filter="text (*.txt)")
        if filepath == "":
            return

        fo = open(filepath, "r")
        title_line = fo.readline()  # first line is Titles
        title_line_sp = title_line.split(" ")
        title_gonio_index = 0
        title_proton_index = 0
        title_index = 0
        # Find protons and gonio
        for st_title in title_line_sp:
            a_title = st_title.strip()
            if a_title != "":
                if a_title.find("start") >= 0 or a_title.find("end") >= 0:
                    title_index += 2
                else:
                    title_index += 1
                if a_title.find("protons") >= 0:
                    title_proton_index = title_index - 1
                if a_title.find("gonio") >= 0:
                    title_gonio_index = title_index - 1

        runinfo_list = fo.readlines()
        fo.close()

        # Get First angle
        gonio_atZero_txt = self.StepByStepParams[0].text().strip()
        if gonio_atZero_txt != "":
            gonio_atZero = float(gonio_atZero_txt)
        else:
            gonio_atZero = 0.0

        # Get the number of list
        nLine = self.lstRunInfo.topLevelItemCount()

        # index = 0
        index = len(self.main.RunList)
        for i, a_runinfo in enumerate(runinfo_list):
            # A head charactore of a line is '#", ignored.
            if a_runinfo.find("#") == 0:
                continue
            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) > title_gonio_index:
                run_no_st = a_line_items[0]
                protons_st = a_line_items[title_proton_index]
                gonio_st = a_line_items[title_gonio_index]
                current_angle = round((float(gonio_st) - gonio_atZero), 3)
                gonio_key = "%08.3f" % (float(gonio_st))
                protons = float(protons_st)

                if (protons < 0.0):
                    protons = -1000000.0
                # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
                if gonio_key not in self.main.RunList:
                    new_line = QtWidgets.QTreeWidgetItem()
                    new_line.setIcon(0, self.statusImage[1])
                    new_line.setText(0, "%8.3f" % (current_angle))
                    new_line.setText(1, run_no_st)
                    self.lstRunInfo.addTopLevelItem(new_line)
                    self.main.RunList[gonio_key] = (
                        1, run_no_st, current_angle, protons, index)
                    index += 1
                else:
                    ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
                    # if same runNo, ignored
                    ex_run_list = ex_runs.split(",")
                    isUniqueRunNo = True
                    for a_run in ex_run_list:
                        if a_run == run_no_st:
                            isUniqueRunNo = False
                            break
                    # if data with runNo was not imported
                    if isUniqueRunNo:
                        ex_runs += ",{}".format(run_no_st)
                        ex_protons += protons
                        self.main.RunList[gonio_key] = (
                            1, ex_runs, ex_angle, ex_protons, ex_ind)
                        self.lstRunInfo.topLevelItem(
                            ex_ind).setText(1, ex_runs)
            else:
                return

        # Turn On Project Button on MainPanel
        for btn_ctrl in self.main.ButtonCtrlList:
            btn_ctrl.setEnabled(False)

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

        gonio_atZero = float(self.StepByStepParams[0].text().strip())
        for gonio_key in self.main.RunList:
            ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
            calc_angle = round((float(gonio_key) - gonio_atZero), 3)
            self.lstRunInfo.topLevelItem(ex_ind).setText(
                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].text().strip()
        gonio = float(self.StepByStepParams[2].text().strip())
        protons = float(self.StepByStepParams[3].text().strip())
        runNo = int(runNo_st)
        if runNo <= 0:
            raise UserWarning("Run Number is invalid.")

        gonio_key = "%08.3f" % gonio
        gonio_atZero = float(self.StepByStepParams[0].text().strip())
        calc_angle = float(gonio_key) - gonio_atZero
        if gonio_key not in self.main.RunList:
            new_line = QtWidgets.QTreeWidgetItem()
            new_line.setIcon(0, self.statusImage[1])
            new_line.setText(0, "%8.3f" % (calc_angle))
            new_line.setText(1, runNo_st)
            self.lstRunInfo.addTopLevelItem(new_line)
            index = self.lstRunInfo.topLevelItemCount() - 1
            self.main.RunList[gonio_key] = (
                1, runNo_st, calc_angle, protons, index)
        else:
            ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.main.RunList[gonio_key]
            ex_runs += ",{}".format(runNo_st)
            ex_protons += protons
            self.main.RunList[gonio_key] = (
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind)
            self.lstRunInfo.topLevelItem(ex_ind).setText(1, ex_runs)

    ##################################
    def OnSelectMaskFile(self, evt=None):
        """
        """
        print("OnSelectMaskFile")
        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u"Choose mask file...", os.getcwd(), filter="mask (*.txt *.xml)")
        if filepath == "":
            return

        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].setText("%s" % (found_filepath))
        else:
            self.ReductionParams[4].setText("%s" % (bname))

    ##################################
    def OnSelectDRScript(self, evt=None):
        """
        """
        print("OnSelectDRScript")
        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getOpenFileName(
            self, u"Choose Data Reduction script file...", os.getcwd(), filter="python (*.py)")
        if filepath == "":
            return
        if self.CheckDRScript(filepath):
            bname = os.path.basename(filepath)
            dname = os.path.dirname(filepath)
            if dname == os.getcwd():
                self.DRScriptPathLabel.setText("{}(Current Dir)".format(bname))
            else:
                self.DRScriptPathLabel.setText("{}({})".format(bname, dname))
            self.DRScriptPath = filepath
        else:
            msg = "Failed to import Script File"
            dlg = QtWidgets.QMessageBox().critical(
                None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)

    ##################################
    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 "DataReductionContRot" in dir(TF):
                    del TF
                    return True
            else:
                if "DataReduction" in dir(TF):
                    del TF
                    return True
            del TF
            return False
            """
            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/python3
# -*- coding: utf-8 -*-
import Cmm
def DataReductionContRot( DAT, phi, maskFile, normFactor, deteeffi ):
    """
    DataReduction Script Template of D4MatSlicer2 for Continuous Rotation method

    @param DAT        (ElementContainerMatrix) Data at angle of Phi
    @param phi        (float) Phi ( angle around Y axis )
    @param maskFile   (string) file name or file path to mask file
    @param normFactor (float) normarization factor
    @param deteffi    (string)
    @return ElementContainerMatrix : valiable name must be 'DAT'
    """
    ######################### Editable #########################
    Cmm.dHWCorrection(dat=DAT)
    Cmm.SolidAngleCorrection(dat=DAT)
    Cmm.KiKfCorrection(dat=DAT)
    Cmm.DoMask(dat=DAT,filename=maskFile)
    Cmm.NormByKickers(dat=DAT,factor=normFactor)
    Cmm.DetectorEffi(dat=DAT, dataFile=deteeffi)
    print("##### phi, DAT.PutSize() = %g, %d"%(phi,DAT.PutSize()))

    ############################################################
    return DAT
'''
        else:
            title = "Step-By-Step Method"
            script = '''#!/usr/bin/python3
# -*- coding: utf-8 -*-
import DR
def DataReduction( runNos, Ei, hw_min, hw_max, hw_bin, maskFile, normFactor, timeindepback, deteffi ):
    """
    DataReduction Script Template of D4MatSlicer2 for Step-by-Step method
    @param runNos     (string) Run Numbers "<runNo1>,<runNo2>,..." or "<runNo1>-<runNo2>"
    @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 maskFile   (string) file name or file path to mask file
    @param normFactor (float) normarization factor
    @param timeindepback (string) parameter for time-independed background
    @param deteffi    (string)
    @return ElementContainerMatrix : valiable name must be 'DAT'
    """
    ######################### Editable #########################

    DAT = DR.GetDataOfMonochroEi3(runNos,Ei,hw_bin,"%g %g"%(hw_min,hw_max),MaskFile=maskFile,NormFactor=normFactor,TimeDepBack=timeindepback, DetEffi=deteffi)

    ############################################################
    return DAT
'''
        # open dialog
        filepath, filt = QtWidgets.QFileDialog().getSaveFileName(
            self, u"Set Data Reduction script ...", os.getcwd(), filter="Python (*.py)")
        if filepath == "":
            return

        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.setText("{}(Current Dir)".format(bname))
        else:
            self.DRScriptPathLabel.setText("{}({})".format(bname, dname))

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

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

###############################################

####################################


class ExecDataReductionContRot(object):
    def __init__(self, parent, lock=None, isOnLine=False):
        """
        """

        self.parent = parent
        self.lock = lock
        self.status = 0
        self.index = 0
        self.isOnLine = isOnLine

    def OnStart(self, DataConverter, D4MatR, DataStore, isRefresh=False, KIC=None):
        """
        """
        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, KIC,))
        th.daemon = True
        th.start()
        if self.DataStore.Script != "":
            pdg = QtWidgets.QProgressDialog(
                "Make D4Mat2 data", "Abort", 0, self.num_of_cases, self.parent)
            pdg.setWindowModality(QtCore.Qt.WindowModal)
            while(True):
                time.sleep(0.5)
                if (self.index >= self.num_of_cases):
                    break
                if pdg.wasCanceled():
                    break
                if self.status < 0:
                    break
                pdg.setValue(int(self.index))
            pdg.close()

    def __ExecFuncOffLine(self, num_of_cases, cond_list, KIC):
        """
        """

        IND = Manyo.MakeUInt4Vector()
        PHI = Manyo.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]
        # print("#[inamura 220516] num_of_cases = {}".format(num_of_cases))
        # print("#[inamura 220516] cond_list.size() = {}".format(cond_list.size()))
        # print("#[inamura 220516] KIC.size() = {}".format(KIC.size()))
        # for i in range(cond_list.size()):
        #    print( cond_list[i] )
        hh = Manyo.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 mask_path.upper() == "DEFAULT":
            mask_path = PutDefaultMaskFile(int(self.DataConverter._runNumber))

        if self.DataStore.Script == "":
            ret = self.D4MatR.ImportEcmsContRot(
                self.DataConverter, IND, PHI, KIC, mask_path, dOmega, self.DataStore.NormFactor, self.DataStore.DetEffi, 15)
            self.index = num_of_cases
        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 "DataReductionContRot" not 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 = Manyo.ElementContainerMatrix()
                self.DataConverter.SetElementContainerMatrix(ecm, IND[i])
                ecm.PutHeaderPointer().OverWrite(
                    mu.UTSUSEMI_KEY_HEAD_KICKERCOUNT, KIC[IND[i]])
                ecm_after_script = self.DataReductionByScript(
                    ecm, PHI[i], dOmega)

                # self.D4MatR.ImportEcmContRot( ecm_after_script, IND[i], PHI[i] )
                self.D4MatR.ImportEcmStepByStep(
                    ecm_after_script, PHI[i], "{}".format(IND[i]), False)

                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 = Manyo.MakeUInt4Vector()
        PHI = Manyo.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 = Manyo.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 mask_path == "default":
            mask_path = PutDefaultMaskFile(int(self.DataConverter._RunNo))

        if self.DataStore.Script == "":
            # ret = self.D4MatR.ImportEcmsContRotPseudoOnLine( self.DataConverter, IND, PHI, mask_path, dOmega, self.isRefresh )
            ret = self.D4MatR.ImportEcmsContRotPseudoOnLine(
                self.DataConverter, IND, PHI, mask_path, dOmega, self.DataStore.NormFactor, self.DataStore.DetEffi, self.isRefresh, 15)
        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 "DataReductionContRot" not 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 = Manyo.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()
        del URI

        mask_file = self.DataStore.MaskFile
        if self.DataStore.MaskFile.upper() == "DEFAULT":
            if ecm.PutHeaderPointer().CheckKey(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER) == 1:
                runNo = ecm.PutHeaderPointer().PutInt4(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)
                mask_file = PutDefaultMaskFile(int(runNo))
            else:
                mask_file = ""
        """
        if mask_file!="":
            MSK = mu.UtsusemiSetMask(ecm, mask_file)
            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)

        URI.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, mask_file, self.DataStore.NormFactor, self.DataStore.DetEffi)
        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.daemon = 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
        normfactor = self.DataStoreStepByStep.NormFactor
        timeindepback = self.DataStoreStepByStep.TimeIndepBack
        deteffi = self.DataStoreStepByStep.DetEffi
        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)

        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))
            # NormFactor = -1.0*NormFactor/1000000.0
            NormFactor = -1.0 * NormFactor / normfactor
            if normfactor < 0.0:
                NormFactor = normfactor
            print("NormFactor={}".format(NormFactor))
            if TF is None:
                ecm = DR.GetDataOfMonochroEi3(runs, Ei, dhw, "%g %g" % (
                    hw_min, hw_max), MaskFile=maskfile, NormFactor=NormFactor, TimeDepBack=timeindepback, DetEffi=deteffi)
            else:
                print("##### DR Script = %s" % (script))
                if maskfile.upper() == "DEFAULT":
                    runs_sp_m = runs.split("-")
                    runs_sp_c = runs.split(",")
                    mask_run = 0
                    if len(runs_sp_m) > len(runs_sp_c):
                        mask_run = int(runs_sp_m[0])
                    else:
                        mask_run = int(runs_sp_c[0])
                    maskfile = PutDefaultMaskFile(mask_run)
                # ecm = TF.DataReduction( runNo, Ei, hw_min, hw_max, dhw, NormFactor, maskfile )
                ecm = TF.DataReduction(
                    runs, Ei, hw_min, hw_max, dhw, maskfile, NormFactor, timeindepback, deteffi)

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

        self.status = -1

class ExecSliceMemSave(object):
    def __init__(self, parent, lock=None):
        """
        """
        self.parent = parent
        self.lock = lock
        self.retval = None
        self.status = -1

    def OnStart(self):
        """
        """
        # サブスレッドスタート
        self.status = 0
        th = threading.Thread(target=self.__ExecFunc, args=())
        th.daemon = True
        th.start()

    def __ExecFunc(self):
        """
        """
        # get slice params
        (VS1, VS2, VS3, VS4, VST, VSF) = self.parent.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.parent.ShowMessage("SliceContRotDat: Invalid Axis info X,Y,T")
            return

        # get units for axes
        VUT = Manyo.MakeStringVector(4)
        for i in range(4):
            VUT[i] = self.parent.ProjectionUnitCtrl[i].text()

        time.sleep(1.0) # for update GUI

        # slice
        # eca_ret = self.D4MatR.Slice2d(VS1, VS2, VS3, VS4, VST, VSF, VUT)
        eca_ret = Manyo.ElementContainerArray()
        if self.parent.D4MatR.Slice2d(eca_ret, VS1, VS2, VS3, VS4, VST, VSF, VUT):
            self.retval = eca_ret
        else:
            self.status = -1
            return


###############################################


class WaitDialog(QtWidgets.QDialog):
    def __init__(self, parent=None, title="", comment=""):
        super(WaitDialog, self).__init__(parent)
        label1 = QtWidgets.QLabel(comment)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(label1)
        self.setLayout(layout)

        #self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.setWindowTitle(title)
        self.resize(200, 100)
        self.setModal(True)
        self.show()
        #self.raise_()

###############################################


class D4Mat2Slicer(QtWidgets.QMainWindow):
    __version__ = 'v210305'

    def __init__(self, parent):
        """
        """
        # Make window and set Event handler
        super(D4Mat2Slicer, self).__init__(None)
        self.frame = Ui_MainWindow()
        if self.frame is None:
            return
        self.frame.setupUi(self)

        # bind button
        self.btLoadData = self.findChild(QtWidgets.QPushButton, u'btLoadData')
        self.btLoadData.clicked.connect(self.OnLoadData)
        self.btSaveData = self.findChild(QtWidgets.QPushButton, u'btSaveData')
        self.btSaveData.clicked.connect(self.OnSaveData)
        self.cbSaveDataWithComp = self.findChild(QtWidgets.QCheckBox, u'cbSaveDataWithComp')
        self.cbSaveDataWithComp.setChecked(True)
        self.btSaveData.setEnabled(False)
        self.cbSaveDataWithComp.setEnabled(False)
        self.btLoadXtalParam = self.findChild(
            QtWidgets.QPushButton, u"btLoadXtalParam")
        self.btLoadXtalParam.clicked.connect(self.OnLoadXtalParam)
        self.btSaveXtalParam = self.findChild(
            QtWidgets.QPushButton, u"btSaveXtalParam")
        self.btSaveXtalParam.clicked.connect(self.OnSaveXtalParam)
        self.btAdvXtalParam = self.findChild(
            QtWidgets.QPushButton, u"btAdvXtalParam")
        self.btAdvXtalParam.clicked.connect(self.OnAdvXtalParam)

        self.BtnReductionInfo = self.findChild(
            QtWidgets.QPushButton, u'btDataReduction')
        self.BtnReductionInfo.clicked.connect(self.OnOpenDataReduction)

        self.ButtonCtrlList = [None, None, None, None, None, None, None, None]
        self.ButtonCtrlList[0] = self.findChild(
            QtWidgets.QPushButton, u'btProjectionAll')
        self.ButtonCtrlList[1] = self.findChild(
            QtWidgets.QPushButton, u'btProjectionClear')
        self.ButtonCtrlList[2] = self.findChild(
            QtWidgets.QPushButton, u'btAutoFill')
        self.ButtonCtrlList[3] = self.findChild(
            QtWidgets.QPushButton, u'btAutoFillAx1')
        self.ButtonCtrlList[4] = self.findChild(
            QtWidgets.QPushButton, u'btAutoFillAx2')
        self.ButtonCtrlList[5] = self.findChild(
            QtWidgets.QPushButton, u'btAutoFillAx3')
        self.ButtonCtrlList[6] = self.findChild(
            QtWidgets.QPushButton, u'btAutoFillAx4')
        self.ButtonCtrlList[7] = self.findChild(
            QtWidgets.QPushButton, u'btDataConversion')
        self.ButtonCtrlList[0].clicked.connect(self.OnProjForAll)
        self.ButtonCtrlList[1].clicked.connect(self.OnProjClearAll)
        self.ButtonCtrlList[2].clicked.connect(self.OnAutoFill)
        self.ButtonCtrlList[3].clicked.connect(
            lambda: self.OnAutoFillAxes(self.ButtonCtrlList[3]))
        self.ButtonCtrlList[4].clicked.connect(
            lambda: self.OnAutoFillAxes(self.ButtonCtrlList[4]))
        self.ButtonCtrlList[5].clicked.connect(
            lambda: self.OnAutoFillAxes(self.ButtonCtrlList[5]))
        self.ButtonCtrlList[6].clicked.connect(
            lambda: self.OnAutoFillAxes(self.ButtonCtrlList[6]))
        self.ButtonCtrlList[7].clicked.connect(self.OnDataConvert)

        self.cbDataConv = self.findChild(
            QtWidgets.QComboBox, u'cbDataConversions')
        self.cbDataConv.currentIndexChanged.connect(self.OnChangedConvType)
        self.cbDataConv.setEnabled(True)

        self.SliceButtonCtrlList = [None, None]
        self.SliceButtonCtrlList[0] = self.findChild(
            QtWidgets.QPushButton, u'btSlice')
        self.SliceButtonCtrlList[1] = self.findChild(
            QtWidgets.QPushButton, u'btSlice3D')
        self.SliceButtonCtrlList[0].clicked.connect(self.OnSlice)
        self.SliceButtonCtrlList[1].clicked.connect(self.OnSlice3D)

        self.SliceButtonCtrlList[0].setEnabled(False)
        self.SliceButtonCtrlList[1].setEnabled(False)

        for btn_ctrl in self.ButtonCtrlList:
            btn_ctrl.setEnabled(False)

        # Memory Save mode
        self.cbMemorySaveMode = self.findChild(QtWidgets.QCheckBox, u'ckMemorySaveMode')
        self.cbMemorySaveMode.stateChanged.connect(self.OnChangeMemSaveMode)

        # On-Line Mode Setting -->
        self.txtRunNo = self.findChild(QtWidgets.QLabel, u'txtRunNo')
        self.txtExpInfo = self.findChild(QtWidgets.QLabel, u'txtExpInfo')
        self.BtnDRExec = self.findChild(QtWidgets.QPushButton, u'btDRExec')
        self.BtnDRExec.clicked.connect(self.OnDRExec)
        self.BtnDRExec.setEnabled(False)
        self.OnLineModeBox = self.findChild(
            QtWidgets.QGroupBox, u'gbOnLineBox')
        self.OnLineModeBtn = self.findChild(
            QtWidgets.QToolButton, u'tgbOnLineMode')
        self.OnLineModeBtn.setCheckable(True)
        self.OnLineModeBtn.clicked.connect(self.OnClickOnLineMode)
        self.OnLineModeBtn.setEnabled(False)
        self.OnLineModeBtnCtrlList = [None, None]
        self.OnLineModeBtnCtrlList[0] = self.findChild(
            QtWidgets.QPushButton, u'btAUupdate')
        self.OnLineModeBtnCtrlList[1] = self.findChild(
            QtWidgets.QPushButton, u'btAUstart')
        self.OnLineModeBtnCtrlList[0].clicked.connect(self.OnAUupdate)
        self.OnLineModeBtnCtrlList[1].clicked.connect(self.OnAUstart)
        self.OnLineModeBtnCtrlList[0].setEnabled(False)
        self.OnLineModeBtnCtrlList[1].setEnabled(False)
        self.OnLineModeCkbCtrlList = [None, None, None]
        self.OnLineModeCkbCtrlList[0] = self.findChild(
            QtWidgets.QCheckBox, u'ckAUwithReduction')
        self.OnLineModeCkbCtrlList[1] = self.findChild(
            QtWidgets.QCheckBox, u'ckAUwithProjection')
        self.OnLineModeCkbCtrlList[2] = self.findChild(
            QtWidgets.QCheckBox, u'ckAUwithSlice')
        self.OnLineModeCkbCtrlList[0].setEnabled(False)
        self.OnLineModeCkbCtrlList[0].setChecked(True)
        self.OnLineModeCkbCtrlList[1].stateChanged.connect(
            self.OnAUwithProjection)
        self.OnLineModeCkbCtrlList[2].stateChanged.connect(self.OnAUwithSlice)
        self.OnLineModeCkbCtrlList[1].setEnabled(False)
        self.OnLineModeCkbCtrlList[2].setEnabled(False)

        self.AUIntervalTimeTxt = self.findChild(
            QtWidgets.QLineEdit, u'txAUIntervalTime')
        self.AUIntervalTimeTxt.setEnabled(False)
        self.AUIntervalUnit = self.findChild(QtWidgets.QLabel, u'txtAUunit')
        self.AUIntervalUnit.setEnabled(False)

        self.doneOnLineModeFirstPrmSet = False
        self.doneD4MatPrmSet = False
        self.IsOnLineMode = False
        self.IsAutoUpdateMode = False
        self.isEnableSlice = False

        # sample rotation
        self.chrotax1 = self.findChild(QtWidgets.QComboBox, u'chRotateAxis1st')
        self.chrotax2 = self.findChild(QtWidgets.QComboBox, u'chRotateAxis2nd')
        self.chrotax3 = self.findChild(QtWidgets.QComboBox, u'chRotateAxis3rd')
        self.chrotax1.activated.connect(
            lambda: self.OnChoiceRotateAxes2(self.chrotax1))
        self.chrotax2.activated.connect(
            lambda: self.OnChoiceRotateAxes2(self.chrotax2))
        self.chrotax3.activated.connect(
            lambda: self.OnChoiceRotateAxes2(self.chrotax3))
        self.chRotationSteps = [self.chrotax1, self.chrotax2, self.chrotax3]

        # Sample Info Panel control
        self.SampleInfoCtrl = []
        for i in range(15):
            key = u"txt%d_p1" % (i + 1)
            self.SampleInfoCtrl.append(
                self.findChild(QtWidgets.QLineEdit, key))

        # Projection Info Panel control
        # KEY="%08.3f"@gonio, cont = ( status, "%s,%s"@(runNos), calc_angle, protons, indexOfList )
        self.RunList = {}
        self.ProjectionCtrl = []
        self.ProjectionUnitCtrl = []
        for i in range(4):
            uv0 = []
            for j in range(5):
                key = u"txt%d_p2" % (i * 5 + j + 1)
                uv0.append(self.findChild(QtWidgets.QLineEdit, key))
            self.ProjectionCtrl.append(uv0)
            key_unit = "txt{:2d}_p2".format(21 + i)
            self.ProjectionUnitCtrl.append(
                self.findChild(QtWidgets.QLineEdit, key_unit))

        # Slice Panel control
        self.SliceAxis = []
        self.SliceRange = []
        self.SliceFold = []
        self.DiagFoldAxesList = []

        self.DiagFoldType = self.findChild(
            QtWidgets.QComboBox, u'cbDiagFoldType')
        self.DiagFoldType.activated.connect(self.OnChangeDiagFold)

        for i in range(4):
            self.SliceAxis.append(self.findChild(
                QtWidgets.QComboBox, u'v%dch' % (i + 1)))
            self.SliceFold.append(self.findChild(
                QtWidgets.QLineEdit, u"txtFold%d" % (i + 1)))

        for i in range(3):
            self.DiagFoldAxesList.append(self.findChild(
                QtWidgets.QComboBox, u"cbDiagFoldAx{:1d}".format((i + 1))))
            self.DiagFoldAxesList[-1].activated.connect(self.OnChangeDiagFoldAx)

        for i in range(12):
            self.SliceRange.append(self.findChild(
                QtWidgets.QLineEdit, u'txt%d_p3' % (i + 1)))

        # Axis type bind
        # for i in range(4):
        #    self.SliceAxis[i].activated.connect(lambda:self.OnChangeSliceAxis(self.SliceAxis[i]))
        self.SliceAxis[0].activated.connect(
            lambda: self.OnChangeSliceAxis(self.SliceAxis[0]))
        self.SliceAxis[1].activated.connect(
            lambda: self.OnChangeSliceAxis(self.SliceAxis[1]))
        self.SliceAxis[2].activated.connect(
            lambda: self.OnChangeSliceAxis(self.SliceAxis[2]))
        self.SliceAxis[3].activated.connect(
            lambda: self.OnChangeSliceAxis(self.SliceAxis[3]))

        # Reduction function
        self.DataReductionPanel = None
        self.DataConverter = None
        # self.DataStoreStepByStep = []
        self.DataStoreStepByStep = None
        self.RunListStepByStep = []
        self.DataStoreContRot = DataStoreContRot()

        self.IsReadyProjection = False  # [inamura 170215]

        # Method Continuous or Step-by-Step
        self.IsContinuousMethod = True

        self.lock = _thread.allocate_lock()

        # Initialize
        self.show()

        self.WorkFolderPath = mu.UtsusemiEnvGetWorkDir()
        if self.WorkFolderPath == "":
            self.WorkFolderPath = os.getcwd()
        os.chdir(self.WorkFolderPath)
        self.M2Plot = None

        self.D4MatR = mu.UtsusemiD4Matrix2()
        if "UTSUSEMI_D4MAT2_MEMSAVE" in os.environ:
            memSave_s = os.environ["UTSUSEMI_D4MAT2_MEMSAVE"]
            if memSave_s == "y":
                self.D4MatR.SetMemorySaving(True)
            else:
                self.D4MatR.SetMemorySaving(False)

        if mu.UtsusemiEnvGetInstCode() == "DNA":
            self.D4MatR.isDirectGeometry = False

        self.cbMemorySaveMode.setChecked(self.D4MatR.isMemSaveMode)

        self.VCP = mu.UtsusemiSqeCalcXtalParams()

        # self.ExecProjection = ExecProjection(self.lock)
        self.ExecDataReductionStepByStep = ExecDataReductionStepByStep(
            self.lock)
        self.ExecDataReductionContRot = ExecDataReductionContRot(
            self, self.lock, False)  # Off-line

        self.SliceViewer3d = None
        self.InitializeValues()

    #################################
    def closeEvent(self, event):
        """
        ダイアログクローズイベント処理
        closeEventのOverride
        @retval 無し
        """
        if self.DataReductionPanel is not None:
            self.DataReductionPanel.close()
        # リスナー登録を削除
        # self.ifi.DelListner(self.lIndex)
        event.accept()
    #################################

    def InitializeValues(self):
        """
        """
        self.SampleInfoCtrl[0].setText("{:g}".format(1.0))  # a
        self.SampleInfoCtrl[1].setText("{:g}".format(1.0))  # b
        self.SampleInfoCtrl[2].setText("{:g}".format(1.0))  # c
        self.SampleInfoCtrl[3].setText("{:g}".format(90.0))  # alpha
        self.SampleInfoCtrl[4].setText("{:g}".format(90.0))  # beta
        self.SampleInfoCtrl[5].setText("{:g}".format(90.0))  # gamma
        self.SampleInfoCtrl[6].setText("{:g}".format(0.0))  # Uh
        self.SampleInfoCtrl[7].setText("{:g}".format(1.0))  # Uk
        self.SampleInfoCtrl[8].setText("{:g}".format(0.0))  # Ul
        self.SampleInfoCtrl[9].setText("{:g}".format(0.0))  # Vh
        self.SampleInfoCtrl[10].setText("{:g}".format(0.0))  # Vk
        self.SampleInfoCtrl[11].setText("{:g}".format(1.0))  # Vl

        self.ProjectionCtrl[0][0].setText("{:g}".format(1.0))  # ax1
        self.ProjectionCtrl[0][1].setText("{:g}".format(0.0))  # ax1
        self.ProjectionCtrl[0][2].setText("{:g}".format(0.0))  # ax1
        self.ProjectionCtrl[0][4].setText("{:s}".format("Qa"))  # Label
        self.ProjectionCtrl[1][0].setText("{:g}".format(0.0))  # ax2
        self.ProjectionCtrl[1][1].setText("{:g}".format(1.0))  # ax2
        self.ProjectionCtrl[1][2].setText("{:g}".format(0.0))  # ax2
        self.ProjectionCtrl[1][4].setText("{:s}".format("Qb"))  # Label
        self.ProjectionCtrl[2][0].setText("{:g}".format(0.0))  # ax3
        self.ProjectionCtrl[2][1].setText("{:g}".format(0.0))  # ax3
        self.ProjectionCtrl[2][2].setText("{:g}".format(1.0))  # ax3
        self.ProjectionCtrl[2][4].setText("{:s}".format("Qc"))  # Label
        self.ProjectionCtrl[3][3].setText("{:g}".format(1.0))  # ax4
        self.ProjectionCtrl[3][4].setText("{:s}".format("Energy"))  # Label
        self.ProjectionUnitCtrl[0].setText("{:s}".format("rlu"))
        self.ProjectionUnitCtrl[1].setText("{:s}".format("rlu"))
        self.ProjectionUnitCtrl[2].setText("{:s}".format("rlu"))
        self.ProjectionUnitCtrl[3].setText("{:s}".format("meV"))

        self.SliceRange[0].setText("{:g}".format(-1.0))  # ax1 from
        self.SliceRange[1].setText("{:g}".format(1.0))  # ax1 to
        self.SliceRange[2].setText("{:g}".format(0.1))  # ax1 step
        self.SliceRange[3].setText("{:g}".format(-1.0))  # ax2 from
        self.SliceRange[4].setText("{:g}".format(1.0))  # ax2 to
        self.SliceRange[5].setText("{:g}".format(0.1))  # ax2 step
        self.SliceRange[6].setText("{:g}".format(-1.0))  # ax3 from
        self.SliceRange[7].setText("{:g}".format(1.0))  # ax3 to
        self.SliceRange[8].setText("{:g}".format(0.1))  # ax3 step
        self.SliceRange[9].setText("{:g}".format(-1.0))  # ax4 from
        self.SliceRange[10].setText("{:g}".format(1.0))  # ax4 to
        self.SliceRange[11].setText("{:g}".format(0.1))  # ax4 step

        for i in range(4):
            self.SliceFold[i].setText("{:g}".format(-1))
        for obj in self.DiagFoldAxesList:
            obj.setCurrentIndex(0)
            obj.setEnabled(False)
        self.findChild(QtWidgets.QComboBox, u"cbDiagFoldAx4").setEnabled(False)

    #################################
    def OnChangeMemSaveMode(self, evt=None):
        """
        """
        if self.cbMemorySaveMode.checkState() == QtCore.Qt.Checked:
            self.D4MatR.SetMemorySaving(True)
        else:
            self.D4MatR.SetMemorySaving(False)

    #################################
    def OnLoadData(self, evt=None):
        """
        """
        self.ShowMessage("OnLoadData")
        # Turn the face color of [Load] to red while loading data
        btLoadData_originstylesheet = self.btLoadData.styleSheet()
        self.btLoadData.setStyleSheet('background-color: red;')
        filepath, filt = QtWidgets.QFileDialog.getOpenFileName(
            self, "Open Data file ...", os.getcwd(), filter='d4m, d4mz (*.d4m *.d4mz)')
        if filepath == "":
            # Turn the face color of [Load] to the original one after load data finishes
            self.btLoadData.setStyleSheet(btLoadData_originstylesheet)
            return
        filepath = str(filepath)

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

        self.IsReadyProjection = False
        self.isEnableSlice = False
        self.ButtonCtrlAfterDR(False)
        self.CheckEnableSliceButton()
        if self.D4MatR.LoadData(str(filepath)):
            xp = self.D4MatR.PutXtalParam()
            if xp != "":
                if mu.UtsusemiEnvGetDebugMode():
                    print("LoadData >>> Loaded XtalParam = ")
                    print(xp)
                self.OnLoadXtalParam(input_xml=xp)
        else:
            msg = "Failed to load data file (may be broken)"
            dlg = QtWidgets.QMessageBox().critical(
                None, u"ERROR", msg, QtWidgets.QMessageBox.Ok)
            # Turn the face color of [Load] to the original one after load data finishes
            self.btLoadData.setStyleSheet(btLoadData_originstylesheet)
            return
            #raise UserWarning("Failed to Load data ({})".format(filepath))

        if self.IsContinuousMethod:
            # runNo_st = "%06d [ continuous ]"%(self.DataStoreContRot.RunNo)
            runNo_st = ""
            for a_run, dum in self.DataStoreContRot.RunNoAngleList:
                runNo_st += "{},".format(a_run)
            runNo_st = runNo_st[:-1]
            runNo_st += " [continuous]"
            exp_info = "Ei=%g (meV) / Rot= %.3g:%.3g:%.3g (deg.)" % (self.DataStoreContRot.Ei,
                                                                     self.DataStoreContRot.AngleMin, self.DataStoreContRot.AngleStep, self.DataStoreContRot.AngleMax)
        else:
            runlist = []
            anglist = []
            for a_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[a_key]
                for a_run in ex_runs.split(","):
                    runlist.append(int(a_run))
                anglist.append(round(float(ex_angle), 3))
            runlist.sort()
            anglist.sort()
            runNo_st = "%06d-%06d [StepByStep]" % (runlist[0], runlist[-1])
            exp_info = "Ei=%g (meV)\nAng= %s:%s" % (
                self.DataStoreStepByStep.Ei, anglist[0], anglist[-1])
        self.BtnDRExec.setEnabled(True)
        self.txtRunNo.setText(runNo_st)
        self.txtExpInfo.setText(exp_info)
        self.IsReadyProjection = True
        self.ButtonCtrlAfterDR(True)
        if self.DataReductionPanel is not None:
            self.DataReductionPanel.Initialize()
            if self.D4MatR.Empty():
                pass
            else:
                self.ButtonCtrlList[0].setEnabled(True)
        # Turn the face color of [Load] to the original one after load data finishes
        self.btLoadData.setStyleSheet(btLoadData_originstylesheet)

    #################################
    def OnSaveData(self, evt=None):
        """
        """
        self.ShowMessage("OnSaveData")
        # Turn the face color of [Save] to red while saving data
        btSaveData_originstylesheet = self.btSaveData.styleSheet()
        self.btSaveData.setStyleSheet('background-color: red;')
        withComp = False
        if self.cbSaveDataWithComp.checkState() == QtCore.Qt.Checked:
            withComp = True
        file_ext = "d4m"
        if withComp:
            file_ext = "d4mz"
        filepath, filt = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save Data file ...", os.path.join(os.getcwd(), "Sample.{}".format(file_ext)), filter='{} (*.{})'.format(file_ext, file_ext))
        if filepath == "":
            # Turn the face color of [Save] to the original one after save data finishes
            self.btSaveData.setStyleSheet(btSaveData_originstylesheet)
            return
        filepath = str(filepath)

        if withComp:
            if filepath[-5:] != ".{}".format(file_ext):
                filepath = "{}.{}".format(filepath, file_ext)
        else:
            if filepath[-4:] != ".{}".format(file_ext):
                filepath = "{}.{}".format(filepath, file_ext)

        # self.D4MatR.SetXtalParam(self.OnSaveXtalParam(toFile=False))

        if self.IsContinuousMethod:
            self.D4MatR.SetD4MatMode(0)
            self.D4MatR.SetD4MatDataReductionContinuosClearRunNo()
            for runNo, startAngle in self.DataStoreContRot.RunNoAngleList:
                self.D4MatR.SetD4MatDataReductionContinuosAddRunNo(runNo, startAngle)
            dev_ang_per_enc = self.DataStoreContRot.DeviceEncode
            val_ang_per_enc = self.DataStoreContRot.AngPerEncode
            dio = self.DataStoreContRot.TrigNETinfoDIO
            if self.D4MatR.SetD4MatDataReductionContinuosSetDeviceEncode(dev_ang_per_enc):
                pass
            else:
                self.D4MatR.SetD4MatDataReductionContinuosSetAnglePerEncode(val_ang_per_enc)
            self.D4MatR.SetD4MatDataReductionContinuosSetTrigNETDIO(dio)
            mask_file = self.DataStoreContRot.MaskFile
            norm_factor = self.DataStoreContRot.NormFactor
            time_indep_back = self.DataStoreContRot.TimeIndepBack
            det_effi = self.DataStoreContRot.DetEffi
            DR_script = self.DataStoreContRot.Script
            self.D4MatR.SetD4MatDataReductionOptions(mask_file, norm_factor, time_indep_back, det_effi, DR_script)
        else:
            self.D4MatR.SetD4MatMode(1)
            mask_file = self.DataStoreStepByStep.MaskFile
            norm_factor = self.DataStoreStepByStep.NormFactor
            time_indep_back = self.DataStoreStepByStep.TimeIndepBack
            det_effi = self.DataStoreStepByStep.DetEffi
            DR_script = self.DataStoreStepByStep.Script
            self.D4MatR.SetD4MatDataReductionOptions(mask_file, norm_factor, time_indep_back, det_effi, DR_script)
            self.D4MatR.SetD4MatDataReductionStepByStepGonioAtZero(self.DataStoreStepByStep.GonioAtZero)
            for a_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[a_key]
                self.D4MatR.SetD4MatDataReductionStepByStepAddRunAngles(ex_runs, ex_angle, ex_protons, self.DataStoreStepByStep.NormFactor)

        runNo, DRP, LC, UV, VV, VA, RV, VAT, VAU = self.GetProjectionParam()
        self.D4MatR.SetD4MatSampleInfo(LC, UV, VV, RV)
        self.D4MatR.SetD4MatProjectionAxesInfo(VA, VAT, VAU)
        self.D4MatR.SetD4MatDataReductionInfo(DRP)
        (VS1, VS2, VS3, VS4, VST, VSF) = self.GetParamsForSlice(True)
        self.D4MatR.SetD4MatSliceAxis("0", VST[0], VS1[0], VS1[1], VS1[2], VSF[0])
        self.D4MatR.SetD4MatSliceAxis("1", VST[1], VS2[0], VS2[1], VS2[2], VSF[1])
        self.D4MatR.SetD4MatSliceAxis("2", VST[2], VS3[0], VS3[1], VS3[2], VSF[2])
        self.D4MatR.SetD4MatSliceAxis("3", VST[3], VS4[0], VS4[1], VS4[2], VSF[3])

        """
        withComp = False
        if self.cbSaveDataWithComp.checkState() == QtCore.Qt.Checked:
            withComp = True
        """
        if self.D4MatR.SaveData(str(filepath), withComp):
            # Turn the face color of [Save] to the original one after save data finishes
            self.btSaveData.setStyleSheet(btSaveData_originstylesheet)
            pass
        else:
            self.btLoadSave.setStyleSheet(btSaveData_originstylesheet)
            raise UserWarning("Failed to Save data ({})".format(filepath))

    #################################
    def OnLoadXtalParam(self, evt=None, input_xml="", flags=None, DRflag=True):
        """
        """
        self.ShowMessage("OnLoadXtalParam")
        self.UpdateXtalParamFromGUI()
        # open dialog
        filepath = ""
        if input_xml == "":
            filepath, filt = QtWidgets.QFileDialog.getOpenFileName(
                self, "Open VisCont parameter file ...", os.getcwd(), filter='XML (*.xml)')
            if filepath == "":
                return
            filepath = str(filepath)

            if not os.path.exists(filepath):
                ss = (" Cannot find XML file(%s)" % (filepath))
                self.ShowMessage(ss)
                raise UserWarning(ss)
            self.VCP.LoadFile(filepath)
        else:
            if flags is None:
                self.VCP.DecodeFromXml(input_xml, self.VCP.TOXML_ALL)
            else:
                self.VCP.DecodeFromXml(input_xml, flags)

        # make instance and load file and analysis XML parameter
        lc = self.VCP.PutLatticeConsts()
        uv = self.VCP.PutUVector()
        vv = self.VCP.PutVVector()
        rv = self.VCP.PutRotateSteps()
        ro_list = []
        if rv.size() != 0:
            for i in range(int(rv.size() / 2)):
                ax_dic = {0: "X", 1: "Y", 2: "Z"}
                ax_id = int(rv[2 * i])   # axis 0="X", 1="Y", 2="Y"
                ax_val = rv[2 * i + 1]
                ro_list.append((ax_dic[ax_id], ax_val))

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

        self.SampleInfoCtrl[12].setEnabled(False)
        self.SampleInfoCtrl[13].setEnabled(False)
        self.SampleInfoCtrl[14].setEnabled(False)

        self.chRotationSteps[0].setEnabled(True)
        self.chRotationSteps[0].setCurrentIndex(0)
        self.chRotationSteps[1].setEnabled(False)
        self.chRotationSteps[1].setCurrentIndex(0)
        self.chRotationSteps[2].setEnabled(False)
        self.chRotationSteps[2].setCurrentIndex(0)

        ro_axis_dic = {"Y": 1, "Z": 2, "X": 3}
        for i, a_rot in enumerate(ro_list):
            ax_num = 0
            try:
                ax_num = ro_axis_dic[a_rot[0]]
            except:
                pass
            self.chRotationSteps[i].setEnabled(True)
            self.chRotationSteps[i].setCurrentIndex(ax_num)
            self.SampleInfoCtrl[12 + i].setText("%g" % float(a_rot[1]))
            self.SampleInfoCtrl[12 + i].setEnabled(True)
            if (i + 1) < len(self.chRotationSteps):
                self.chRotationSteps[i + 1].setEnabled(True)

        # Projection infor
        proj_axes = self.VCP.PutViewAxes()
        proj_labels = self.VCP.PutViewAxesLabels()
        proj_units = self.VCP.PutViewAxesUnits()
        for id in range(4):
            for col in range(4):
                self.ProjectionCtrl[id][col].setText(
                    "%g" % (proj_axes[4 * id + col]))
            self.ProjectionCtrl[id][4].setText(proj_labels[id])
            self.ProjectionUnitCtrl[id].setText(proj_units[id])

        # Slicing ranges and steps
        ax_types = self.VCP.PutAxType()
        for id in range(4):
            type = ax_types[id]
            if type in ["x", "y", "p", "t", "z"]:
                range_axis = self.VCP.PutAxRange(id, False)
                self.SliceRange[3 * id + 0].setText("%g" % (range_axis[0]))
                self.SliceRange[3 * id + 1].setText("%g" % (range_axis[1]))
                self.SliceRange[3 * id + 2].setText("%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, "z": 3}
        for i in range(4):
            self.SliceAxis[i].setCurrentIndex(dic[ax_types[i]])

        # folding
        foldings = self.VCP.PutFolding()
        for i in range(4):
            self.SliceFold[i].setText("%g" % (foldings[i]))
        self.SetStepEnable()

        # diagonal folding
        d_folds = self.VCP.PutDiagFolding()
        if d_folds.size() != 0:
            # self.DiagFoldType.setCurrentIndex(d_folds[0])
            self.OnChangeDiagFold(d_folds[0])
            self.DiagFoldAxesList[d_folds[1] - 1].setCurrentIndex(1)
            self.DiagFoldAxesList[d_folds[2] - 1].setCurrentIndex(2)

        if DRflag:
            tt = TreatXmlParams(self)
            if input_xml == "":
                tt.load(filepath)
            else:
                tt.load(input_xml, isInitLoad=False)
            del tt

        # Initialize DataReductionPanel
        if self.DataReductionPanel is not None:
            self.DataReductionPanel.Initialize()

        return

    #################################
    def OnAdvXtalParam(self, evt=None):
        """
        """
        dialog = XtalParamTreatmentDialog(self)

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

    #################################

    def UpdateXtalParamFromGUI(self):
        """
        """
        self.ShowMessage("UpdateXtalParamFromGUI")
        preOnLineMode = self.doneOnLineModeFirstPrmSet
        # Update Params
        if self.DataReductionPanel is not None:
            self.DataReductionPanel.OnReduction(True)
        self.doneOnLineModeFirstPrmSet = preOnLineMode
        # get Lattice consts and U,V vectors
        (Header, axisInfo) = self.GetParamsForProj(isVect=False)
        (LC, UV, VV, VA, RV, VAT, VAU) = self.GetParamsForProj(isVect=True)

        # sliceInfo
        sliceInfo = self.GetParamsForSlice(isVect=False)

        # set parameters
        self.VCP.SetLatticeConstants(LC[0], LC[1], LC[2], LC[3], LC[4], LC[5])
        self.VCP.SetUVvector(UV[0], UV[1], UV[2], VV[0], VV[1], VV[2])

        dic_rot = {0: "X", 1: "Y", 2: "Z"}
        self.VCP.ClearRotationStep()
        for i in range(int(RV.size() / 2)):
            self.VCP.AddRotationStep(dic_rot[RV[2 * i]], float(RV[2 * i + 1]))

        self.VCP.SetProjectionAxes(
            axisInfo[0], axisInfo[1], axisInfo[2], axisInfo[3])
        for i in range(4):
            self.VCP.SetSliceAxis("%1d" % (
                i), sliceInfo[i][0], sliceInfo[i][1], sliceInfo[i][2], sliceInfo[i][3], sliceInfo[i][4])
        # set diag foldings
        diagFoldInfo = [self.DiagFoldType.currentIndex(), -1, -1]
        for i, obj in enumerate(self.DiagFoldAxesList):
            if obj.currentIndex() == 1:
                diagFoldInfo[1] = i + 1
            elif obj.currentIndex() == 2:
                diagFoldInfo[2] = i + 1
        if diagFoldInfo[1] == -1 or diagFoldInfo[2] == -1:
            if diagFoldInfo[0] != 0:
                print("DiagFoldAxes setting is invalid.")
            diagFoldInfo[1] = 0
            diagFoldInfo[2] = 0
        if self.VCP.SetDiagFolding(
            "{:1d}".format(diagFoldInfo[0]), diagFoldInfo[1], diagFoldInfo[2]):
            pass
        else:
            print("ERROR SetDiagFoling")

    #################################
    def OnSaveXtalParam(self, evt=None, toFile=True, filepath="", flags=None, DRflag=True):
        """
        """
        self.ShowMessage("OnSaveXtalParam")
        self.UpdateXtalParamFromGUI()

        if toFile:
            if filepath == "":
                savefile, filt = QtWidgets.QFileDialog.getSaveFileName(
                    self, "Save Crystal Parameter File ...", os.getcwd(), filter='XML (*.xml)')
                if savefile == "":
                    return
                savefile = str(savefile)
            else:
                savefile = filepath
            if savefile[-4:] != ".xml":
                savefile = savefile + ".xml"
            # show parameters to be checked
            # self.VCP.Dump()

            # save to XML file
            if flags is None:
                self.VCP.SaveFile(savefile)
            else:
                self.VCP.SaveFile(savefile, flags)

            if self.BtnDRExec.isEnabled() and DRflag:
                # save D4Mat2Slicer params to XML file
                tt = TreatXmlParams(self)
                tt.add(savefile)
                del tt
        else:
            xml_strings = self.VCP.PutXmlString()
            if self.BtnDRExec.isEnabled():
                tt = TreatXmlParams(self)
                ret_strings = tt.add(xml_strings)
                if type(ret_strings) == bool:
                    return ""
                else:
                    return ret_strings

    #################################
    def GetParamsForProj(self, isVect=False):
        """
        """
        sample = []
        for cont in self.SampleInfoCtrl:
            anum = cont.text().strip()
            if anum == "":
                anum = "0.0"
            try:
                num = float(anum)
            except:
                raise UtilPlot.PlotException(
                    'Common', 'C027', ("Sample Info",))
            sample.append(num)

        Header = {}
        Header[mu.UTSUSEMI_KEY_HEAD_SAMPLE_LATTICECONSTS] = sample[:6]
        Header[mu.UTSUSEMI_KEY_HEAD_SAMPLE_UVECT] = sample[6:9]
        Header[mu.UTSUSEMI_KEY_HEAD_SAMPLE_VVECT] = sample[9:12]

        rotationSteps = []
        for i, rax in zip([0, 1, 2], self.chRotationSteps):
            if rax.isEnabled():
                ax_num = rax.currentIndex()
                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):
                if self.ProjectionCtrl[id][col].text().strip() != "":
                    a_list.append(
                        float(self.ProjectionCtrl[id][col].text().strip()))
                else:
                    a_list.append(0.0)
            a_list.append(self.ProjectionCtrl[id][4].text().strip())
            a_list.append(self.ProjectionUnitCtrl[id].text().strip())
            viewAxisInfo.append(a_list)

        if isVect:
            LC = Manyo.MakeDoubleVector()
            UV = Manyo.MakeDoubleVector()
            VV = Manyo.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 = Manyo.MakeDoubleVector()
            VAT = Manyo.MakeStringVector()
            VAU = Manyo.MakeStringVector()
            for i in range(4):
                for j in range(4):
                    VA.append(viewAxisInfo[i][j])
                VAT.append(viewAxisInfo[i][4])
                VAU.append(viewAxisInfo[i][5])

            RV = Manyo.MakeDoubleVector()
            for i in range(3):

                axis_num = -1.0
                if self.chRotationSteps[i].currentIndex() == 1:   # if Y-axis
                    axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 2:  # if Z-axis
                    axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                elif self.chRotationSteps[i].currentIndex() == 3:  # if X-axis
                    axis_num = 0.0                             # 0 means X-axis in VisualCalcSqe
                else:                                           # if not selected
                    break                                      # move out
                RV.append(axis_num)                # axis number
                RV.append(float(sample[12 + i]))   # angle

                """
                if self.SampleInfoCtrl[12+i].isEnabled():
                    axis_num = -1.0
                    if self.chRotationSteps[i].currentIndex()==1:   # if Y-axis
                        axis_num = 1.0                             # 1 means Y-axis in VisualCalcSqe
                    elif self.chRotationSteps[i].currentIndex()==2: # if Z-axis
                        axis_num = 2.0                             # 2 means Z-axis in VisualCalcSqe
                    elif self.chRotationSteps[i].currentIndex()==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, VAT, VAU)
        else:
            return (Header, viewAxisInfo)

    #################################

    def OnOpenDataReduction(self, evt=None):
        """
        """
        if self.DataReductionPanel is not 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, VAT, VAU) = self.GetParamsForProj(isVect=True)
        (runNoAngleList, dataRedParam) = self.GetDataReductionParam()
        return (runNoAngleList, dataRedParam, LC, UV, VV, VA, RV, VAT, VAU)

    #################################
    def GetDataReductionParam(self):
        """
        """
        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
            runNoAngleList = [(0, 0.0)]

        runNo = 0
        dataRedParam = Manyo.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
            runNoAngleList = self.DataStoreContRot.RunNoAngleList[:]
            # Time slice
            dataRedParam[0] = self.DataStoreContRot.TimeSliceStart
            dataRedParam[1] = self.DataStoreContRot.TimeSliceEnd   # Time slice
            # start angle degree
            dataRedParam[6] = self.DataStoreContRot.AngleMin
            # end angle degree
            dataRedParam[7] = self.DataStoreContRot.AngleMax
            # step angle degree
            dataRedParam[8] = self.DataStoreContRot.AngleStep
        return (runNoAngleList, dataRedParam)

    #################################
    def OnDRExec(self, evt=None):
        """
        """
        self.isEnableSlice = False
        self.IsReadyProjection = False
        self.ButtonCtrlAfterDR(False)
        self.CheckEnableSliceButton()

        # Turn the face color of [Execute] on Data Reduction to red
        self.BtnDRExec_originstylesheet = self.BtnDRExec.styleSheet()
        self.BtnDRExec.setStyleSheet('background-color: red;')
        msg = "Start Data Reduction Process (Maybe it takes some time)"
        ret = QtWidgets.QMessageBox().warning(self, u"Warning", msg,
                                              QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
        if ret == QtWidgets.QMessageBox.Cancel:
            self.BtnDRExec.setStyleSheet(self.BtnDRExec_originstylesheet)
            self.BtnDRExec_originstylesheet = None
            return
        # print( "OnDRExec event" )
        if self.IsContinuousMethod:
            if self.IsOnLineMode:
                print("OnLine Mode")
            else:
                print("Static Mode")
                self.OnLineModeBtn.setEnabled(False)
                self.DRContRotationStatic()
            # Turn the face color of [Execute] on Data Reduction to original
            self.BtnDRExec.setStyleSheet(self.BtnDRExec_originstylesheet)
            self.BtnDRExec_originstylesheet = None
        else:
            print("StepByStep Mode")
            self.DRStepByStep()
            # pass

    #################################
    def DRContRotationStatic(self):
        """
        """
        self.ShowMessage("DataReductionOfContRotation")
        start_time = time.time()
        if isinstance(self.DataConverter, mu.UtsusemiEventDataConverterNeunet):
            self.DataConverter.ResetHistogram()
        else:
            if (self.DataConverter is not 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

        runNoAngleList = self.DataStoreContRot.RunNoAngleList[:]
        # for runNo, st_deg in runNoAngleList:
        DU = D4Mat2Utils()
        runNo = runNoAngleList[0][0]
        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:
            if runNo != 0:
                wfile, dfile = DU.MakeTempInfoFiles(
                    runNo, st_Params, self.DataStoreContRot.TimeIndepBack)
            else:
                wfile, dfile = DU.MakeTempInfoFiles(999999, st_Params)
        # self.ShowMessage( "#### WiringInfo.xml=%s"%wfile )
        # self.ShowMessage( "#### DetectorInfo.xml=%s"%dfile )

        # st_deg = self.DataStoreContRot.AngleStart
        min_deg = self.DataStoreContRot.AngleMin
        max_deg = self.DataStoreContRot.AngleMax
        w_deg = self.DataStoreContRot.AngleStep
        t_start = self.DataStoreContRot.TimeSliceStart
        t_end = self.DataStoreContRot.TimeSliceEnd
        dio = self.DataStoreContRot.TrigNETinfoDIO
        ang_per_enc = self.DataStoreContRot.AngPerEncode
        dev_enc = self.DataStoreContRot.DeviceEncode
        DU = D4Mat2Utils()
        if runNo != 0:
            # data_dir = "/data"
            data_dir = mu.UtsusemiEnvGetDataDir()

            # self.DataConverter.LoadParamFiles( wfile, dfile, cfile )
            self.DataConverter.LoadParamFiles(wfile, dfile)

            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)

            T0List = []
            self.D4MatR.SetD4MatDataReductionContinuosClearRunNo()
            for i in range(len(self.DataStoreContRot.RunNoAngleList)):
                runNoi, st_deg = self.DataStoreContRot.RunNoAngleList[i]
                self.D4MatR.SetD4MatDataReductionContinuosAddRunNo(runNoi, st_deg)
                cfile = DU.MakeCaseInfoFile(
                    st_deg, min_deg, max_deg, w_deg, runNoi, dio, ang_per_enc)
                self.ShowMessage("#### CaseInfo.xml=%s" % cfile)
                self.DataConverter.SetCaseInfoParams(cfile)
                self.DataConverter.LoadTrignetEventFile(runNoi, data_dir, "")
                if i == 0:
                    # self.DataConverter.SetHistAllocation()
                    # self.DataConverter.SetHistAllocation(1)
                    self.DataConverter.SetHistAllocation(2)
                self.DataConverter.LoadEventDataFiles(runNoi, data_dir, "")
                T0List.append(
                    self.DataConverter.PutCaseDecoder().PutNumOfT0ListInCases())

            KIC = Manyo.MakeDoubleVector(T0List[0].size())
            for i in range(T0List[0].size()):
                KIC[i] = 0.0
            for i in range(len(T0List)):
                for j in range(KIC.size()):
                    KIC[j] += T0List[i][j]
            # for i in range(KIC.size()):
            #    print(KIC[i])
            self.D4MatR.SetD4MatRunNo(runNo)
            # self.D4MatR.SetD4MatDataReductionContinuosAddRunNo(runNoi, st_deg)
            runNoAngleList, DRP = self.GetDataReductionParam()
            self.D4MatR.SetD4MatDataReductionInfo(DRP)
            if dev_enc != "":
                if self.D4MatR.SetD4MatDataReductionContinuosSetDeviceEncode(dev_enc):
                    pass
                else:
                    raise UserWarning("Encode device is invalid : " + dev_enc)
            else:
                self.D4MatR.SetD4MatDataReductionContinuosSetAnglePerEncode(ang_per_enc)
            self.ExecDataReductionContRot.OnStart(
                self.DataConverter, self.D4MatR, self.DataStoreContRot, False, KIC)
        else:  # Virtual
            ecm = DR.GetDataOfMonochroEi3("0", self.DataStoreContRot.Ei, self.DataStoreContRot.HW_bin,
                                          "%g %g" % (
                                              self.DataStoreContRot.HW_min, self.DataStoreContRot.HW_max),
                                          MaskFile=self.DataStoreContRot.MaskFile, NormFactor=0)
            angles = Manyo.MakeDoubleVector()
            labels = Manyo.MakeStringVector()
            phi = min_deg
            while(phi <= max_deg):
                angles.push_back(phi)
                labels.push_back("%08.3f" % (phi))
                phi += w_deg
            if self.D4MatR.MakeVirtualD4Mat2(ecm, angles, labels):
                pass
            else:
                raise UserWarning("Failed to make virtual D4Mat2")

        # Turn On Project Button on MainPanel
        self.IsReadyProjection = True
        # self.ButtonCtrlList[0].setEnabled(self.IsReadyProjection)
        self.ButtonCtrlAfterDR(True)
        print("---- Cost time = {}".format(time.time() - start_time))

    #################################
    def DRStepByStep(self):
        """
        """
        self.ShowMessage("DRStepByStep")
        try:
            dam = self.DataReductionPanel.lstRunInfo.topLevelItemCount()
        except:
            self.DataReductionPanel = DataReductionPanel(self.frame, self)
        self.ExecDataReductionStepByStep.OnStart(
            self.DataStoreStepByStep, self.D4MatR, self.RunList)

        # 実行状態を監視するために、0.5秒毎のタイマーをセット
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.OnTimerStepByStep)
        self.timer.start(500)

    #################################
    def OnTimerStepByStep(self, evt=None):
        """
        """
        if self.ExecDataReductionStepByStep.status == -1:
            for i in range(self.DataReductionPanel.lstRunInfo.topLevelItemCount()):
                self.DataReductionPanel.lstRunInfo.topLevelItem(
                    i).setIcon(0, self.DataReductionPanel.statusImage[3])
            self.timer.stop()
            self.IsReadyProjection = True
            self.ButtonCtrlAfterDR(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)
            # Turn face color of [Execute] on Data Reduction to original
            self.BtnDRExec.setStyleSheet(self.BtnDRExec_originstylesheet)
            self.BtnDRExec_originstylesheet = None
        else:
            for i in range(self.ExecDataReductionStepByStep.index):
                self.DataReductionPanel.lstRunInfo.topLevelItem(
                    i).setIcon(0, self.DataReductionPanel.statusImage[3])
            self.DataReductionPanel.lstRunInfo.topLevelItem(
                self.ExecDataReductionStepByStep.index).setIcon(0, self.DataReductionPanel.statusImage[2])

    #################################
    def ButtonCtrlAfterDR(self, flag):
        """
        """
        # All buttons are controled
        self.btSaveData.setEnabled(flag)
        self.cbSaveDataWithComp.setEnabled(flag)

        # Projection is controled
        self.ButtonCtrlList[0].setEnabled(flag)
        self.ButtonCtrlList[1].setEnabled(flag)

        # Autofills are disabled
        self.ButtonCtrlList[2].setEnabled(False)
        self.ButtonCtrlList[3].setEnabled(False)
        self.ButtonCtrlList[4].setEnabled(False)
        self.ButtonCtrlList[5].setEnabled(False)
        self.ButtonCtrlList[6].setEnabled(False)
        # Output are disabled
        if self.cbDataConv.currentIndex() != 0:
            self.ButtonCtrlList[7].setEnabled(flag)

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

    #################################
    def OnProjForAll(self, evt=None):
        """
        """
        if not self.IsReadyProjection:
            return

        self.ShowMessage("OnProjForAll")
        start_time = time.time()
        if self.IsOnLineMode:
            self.OnProjForOnLine()
            print("----- Cost of time = {}".format(time.time() - start_time))
            return
        runNo, DRP, LC, UV, VV, VA, RV, VAT, VAU = self.GetProjectionParam()
        self.D4MatR.SetD4MatSampleInfo(LC, UV, VV, RV)
        self.D4MatR.SetD4MatDataReductionInfo(DRP)

        # self.D4MatR.Projection( VA )
        num_of_angles = self.D4MatR.PutSize()
        pdg = QtWidgets.QProgressDialog(
            "Projection of D4Mat2 data", "Abort", 0, num_of_angles, self)
        pdg.setWindowModality(QtCore.Qt.WindowModal)
        isAborted = False
        for i in range(num_of_angles):
            if self.D4MatR.Projection(i, VA):
                pass
            else:
                print("Error occurs in Projection")
                return
            pdg.setValue(i)
            if pdg.wasCanceled():
                isAborted = True
                break
        pdg.close()
        if isAborted:
            return
        self.ButtonCtrlAfterProj(True)
        self.isEnableSlice = True
        self.isEnableSlice = True
        self.CheckEnableSliceButton()
        self.UpdateXtalParamFromGUI()
        print("----- Cost of time = {}".format(time.time() - start_time))
        return

    #################################
    def OnProjForOnLine(self, evt=None):
        """
        """
        self.isEnableSlice = False
        self.CheckEnableSliceButton()
        runNoAngleList, DRP, LC, UV, VV, VA, RV, VAT, VAU = self.GetProjectionParam()
        if mu.UtsusemiEnvGetDebugMode():
            print("DRP={},{},{},{},{},{},{},{},{}".format(
                DRP[0], DRP[1], DRP[2], DRP[3], DRP[4], DRP[5], DRP[6], DRP[7], DRP[8]))
            print("LC ={},{},{},{},{},{}".format(
                LC[0], LC[1], LC[2], LC[3], LC[4], LC[5]))
            print("UV,VV={},{},{},{},{},{}".format(
                UV[0], UV[1], UV[2], VV[0], VV[1], VV[2]))
            print("VA={},{},{},{}".format(VA[0], VA[1], VA[2], VA[3]))
            print("VA={},{},{},{}".format(VA[4], VA[5], VA[6], VA[7]))
            print("VA={},{},{},{}".format(VA[8], VA[9], VA[10], VA[11]))
            print("VA={},{},{},{}".format(VA[12], VA[13], VA[14], VA[15]))
            p = ""
            for i in range(int(RV.size() / 2)):
                p += str(RV[i * 2 + 0])
                p += ","
                p += str(RV[i * 2 + 1])
                p += ","
            print("RV=" + p)

        runNo = runNoAngleList[0][0]
        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.DataReductContRot = ExecDataReductionContRot(
            self, self.lock, True)
        self.ShowMessage("[OnProjForOnLine]--Projection--")
        self.DataReductContRot.OnStart(
            self.DataConverter, self.D4MatR, self.DataStoreContRot)
        self.ShowMessage("[OnProjForOnLine]--Projection end--")
        self.ButtonCtrlAfterProj(True)
        self.isEnableSlice = True
        self.CheckEnableSliceButton()
        self.UpdateXtalParamFromGUI()
        return

    #################################
    def OnProjClearAll(self, evt=None):
        """
        """
        self.ShowMessage("OnProjClearAll")
        # for run in self.RunList:
        #    run.Status=1

        # clear D4mat
        self.D4MatR.ResetD4mat()

    # [inamura 170215]-->
    def OnChangeDiagFold(self, evt=None):
        """
        """
        # self.ShowMessage(
        #    "OnChangeDiagFold is not working (under constructions)")
        index = 0
        if isinstance(evt, int):
            index = evt
            self.DiagFoldType.setCurrentIndex(index)
        else:
            index = self.DiagFoldType.currentIndex()

        if index == 0:
            for obj in self.DiagFoldAxesList:
                obj.setCurrentIndex(0)
                obj.setEnabled(False)
        else:
            for obj in self.DiagFoldAxesList:
                obj.setEnabled(True)

    def OnChangeDiagFoldAx(self, evt=None):
        """
        """
        self.ShowMessage("OnChangeDiagFoldAx")
        cb_sender = self.sender()
        c_id = cb_sender.currentIndex()
        if c_id == 0:
            return
        for a_cb in self.DiagFoldAxesList:
            if a_cb != cb_sender:
                if a_cb.currentIndex() == c_id:
                    a_cb.setCurrentIndex(0)

    #################################
    def OnAutoFill(self, evt=None):
        """
        """
        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].setText("%7.3f" % (limit_vec[i * 2]))
            self.SliceRange[i * 3 + 1].setText("%7.3f" % (limit_vec[i * 2 + 1]))
        if self.IsContinuousMethod:
            dhw = self.DataStoreContRot.HW_bin
        else:
            dhw = self.DataStoreStepByStep.HW_bin
        self.SliceRange[11].setText("{:7.3f}".format(dhw))

    #########################################
    def OnAutoFillAxes(self, *args):
        try:
            btn = args[0]
            limit_vec = self.D4MatR.GetAxLimit()
            if btn == self.ButtonCtrlList[3]:
                self.SliceRange[0].setText("%7.3f" % (limit_vec[0]))
                self.SliceRange[1].setText("%7.3f" % (limit_vec[1]))
            elif btn == self.ButtonCtrlList[4]:
                self.SliceRange[3].setText("%7.3f" % (limit_vec[2]))
                self.SliceRange[4].setText("%7.3f" % (limit_vec[3]))
            elif btn == self.ButtonCtrlList[5]:
                self.SliceRange[6].setText("%7.3f" % (limit_vec[4]))
                self.SliceRange[7].setText("%7.3f" % (limit_vec[5]))
            elif btn == self.ButtonCtrlList[6]:
                self.SliceRange[9].setText("%7.3f" % (limit_vec[6]))
                self.SliceRange[10].setText("%7.3f" % (limit_vec[7]))
            else:
                pass
        except:
            self.ShowMessage("Do the projection first")

    #################################
    def OnChangeSliceAxis(self, evt=None):
        """
        """
        bt = evt

        # 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.currentIndex() == 2:  # 0..X-Axis, 1..Y-Axis, 2..Thickness
            step_ctrl.setEnabled(False)
        else:
            step_ctrl.setEnabled(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].currentIndex()
                flags[curNo] += 1
            if flags == [1, 1, 2, 0]:
                self.SliceButtonCtrlList[0].setEnabled(True)
                self.SliceButtonCtrlList[1].setEnabled(False)
                if self.cbDataConv.currentIndex() == 0:
                    self.ButtonCtrlList[7].setEnabled(False)
            elif flags == [1, 1, 1, 1]:
                self.SliceButtonCtrlList[0].setEnabled(False)
                self.SliceButtonCtrlList[1].setEnabled(True)
                if self.cbDataConv.currentIndex() == 0:
                    self.ButtonCtrlList[7].setEnabled(False)
            elif flags[2] == 0:
                self.SliceButtonCtrlList[0].setEnabled(False)
                self.SliceButtonCtrlList[1].setEnabled(False)
                if self.cbDataConv.currentIndex() == 0:
                    self.ButtonCtrlList[7].setEnabled(True)
            else:
                self.SliceButtonCtrlList[0].setEnabled(False)
                self.SliceButtonCtrlList[1].setEnabled(False)
                if self.cbDataConv.currentIndex() == 0:
                    self.ButtonCtrlList[7].setEnabled(False)
        else:
            self.SliceButtonCtrlList[0].setEnabled(False)
            self.SliceButtonCtrlList[1].setEnabled(False)
            if self.cbDataConv.currentIndex() == 0:
                self.ButtonCtrlList[7].setEnabled(False)

    #########################################
    def OnSlice(self, *args):
        """
        """
        self.ShowMessage("OnSlice")
        start_time = time.time()
        if self.isEnableSlice:
            if self.D4MatR.isMemSaveMode:
                self.ExecSliceMemSave_start = start_time
                self.SliceMemSave()
            else:
                self.SliceContRotData()
                print("----- Cost of time = {}".format(time.time() - start_time))

        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

        # get units for axes
        VUT = Manyo.MakeStringVector(4)
        for i in range(4):
            VUT[i] = self.ProjectionUnitCtrl[i].text()

        # slice
        # eca_ret = self.D4MatR.Slice2d(VS1, VS2, VS3, VS4, VST, VSF, VUT)
        eca_ret = Manyo.ElementContainerArray()
        if self.D4MatR.Slice2d(eca_ret, VS1, VS2, VS3, VS4, VST, VSF, VUT):
            pass
        else:
            msg = "Slice failed. Invalid parameters, mayge step = 0 ?"
            ret = QtWidgets.QMessageBox().warning(self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        titles = ["", "", "", "", "", "", ""]
        # titles[0]="D4Mat2 Slice"
        run_info = self.txtRunNo.text().split("[")
        exp_info = self.txtExpInfo.text().split("\n")
        if self.IsContinuousMethod:
            titles[0] = "D4Mat2[Continuous] RunNo:{}".format(
                run_info[0].strip())
        else:
            titles[0] = "D4Mat2[StepByStep] RunNo:{}".format(
                run_info[0].strip())
        if len(exp_info) == 1:
            titles[1] = exp_info[0]
        elif len(exp_info) > 1:
            titles[1] = exp_info[0] + "\n"
            titles[1] += (exp_info[1] + "\n")
        for i in range(4):
            label = self.ProjectionCtrl[i][4].text().strip()
            if VST[i] == "x":
                titles[2] = label
                titles[5] = "ax%d" % (i + 1)
            elif VST[i] == "y":
                titles[3] = label
                titles[6] = "ax%d" % (i + 1)
            else:
                titles[1] += "Ax%d:%s " % ((i + 1), label)
                titles[1] += " from %s to %s,\n" % (
                    self.SliceRange[i * 3].text().strip(), self.SliceRange[i * 3 + 1].text().strip())
        Fold = "Fold: "
        for i in range(4):
            if VSF[i] >= 0.0:
                Fold += "Ax{:d}[{:g}],".format((i + 1), VSF[i])
        if Fold != "Fold: ":
            titles[1] += Fold[:-1]
        titles[4] = "Intensity"

        if self.M2Plot is None:
            self.M2Plot = Plot2DMap(0, "D4Mat2Slicer", self)

        self.M2Plot.PlotMap(titles, eca_ret, isRefresh)

    #################################
    def SliceMemSave(self):
        """
        """
        self.ShowMessage("SliceMemSave")
        self.WaitDialog = WaitDialog(self, "Slicing", "Please wait ...")

        self.ExecSliceMemSave = ExecSliceMemSave(self, self.lock)
        self.ExecSliceMemSave.OnStart()

        # 実行状態を監視するために、0.5秒毎のタイマーをセット
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.OnTimerSliceMemSave)
        self.timer.start(500)

    #################################
    def OnTimerSliceMemSave(self, evt=None):
        """
        """
        if self.ExecSliceMemSave.status == -1:
            self.timer.stop()
            msg = "Slice failed. Invalid parameters, mayge step = 0 ?"
            ret = QtWidgets.QMessageBox().warning(self, u"Warning", msg, QtWidgets.QMessageBox.Ok)
            return

        elif self.ExecSliceMemSave.retval is not None:
            self.timer.stop()
            (VS1, VS2, VS3, VS4, VST, VSF) = self.GetParamsForSlice(isVect=True)
            titles = ["", "", "", "", "", "", ""]
            # titles[0]="D4Mat2 Slice"
            run_info = self.txtRunNo.text().split("[")
            exp_info = self.txtExpInfo.text().split("\n")
            if self.IsContinuousMethod:
                titles[0] = "D4Mat2[Continuous] RunNo:{}".format(
                    run_info[0].strip())
            else:
                titles[0] = "D4Mat2[StepByStep] RunNo:{}".format(
                    run_info[0].strip())
            if len(exp_info) == 1:
                titles[1] = exp_info[0]
            elif len(exp_info) > 1:
                titles[1] = exp_info[0] + "\n"
                titles[1] += (exp_info[1] + "\n")
            for i in range(4):
                label = self.ProjectionCtrl[i][4].text().strip()
                if VST[i] == "x":
                    titles[2] = label
                    titles[5] = "ax%d" % (i + 1)
                elif VST[i] == "y":
                    titles[3] = label
                    titles[6] = "ax%d" % (i + 1)
                else:
                    titles[1] += "Ax%d:%s " % ((i + 1), label)
                    titles[1] += " from %s to %s,\n" % (
                        self.SliceRange[i * 3].text().strip(), self.SliceRange[i * 3 + 1].text().strip())
            Fold = "Fold: "
            for i in range(4):
                if VSF[i] >= 0.0:
                    Fold += "Ax{:d}[{:g}],".format((i + 1), VSF[i])
            if Fold != "Fold: ":
                titles[1] += Fold[:-1]
            titles[4] = "Intensity"

            self.WaitDialog.close()

            if self.M2Plot is None:
                self.M2Plot = Plot2DMap(0, "D4Mat2Slicer", self)

            self.M2Plot.PlotMap(titles, self.ExecSliceMemSave.retval, isRefresh=True)
            print("----- Cost of time = {}".format(time.time() - self.ExecSliceMemSave_start))

    #################################
    def OnChangedConvType(self, evt=None):
        """
        """
        conv = self.cbDataConv.currentIndex()
        if conv == 0:
            self.CheckEnableSliceButton()
        elif conv == 1 or conv == 2 or conv == 3:
            self.ButtonCtrlList[7].setEnabled(self.IsReadyProjection)

    #################################
    def OnDataConvert(self, evt=None):
        """
        """
        conv = self.cbDataConv.currentIndex()
        if conv == 0:
            self.OnMakeD4MatFile()
        elif conv == 1:
            self.OnConvSPEFiles(True)
        elif conv == 2:
            self.OnConvSPEFiles(False)
        elif conv == 3:
            self.OnDumpAllAsText()
    #################################

    def OnMakeD4MatFile(self, evt=None):
        """
        """
        self.ShowMessage("OnMakeD4MatFile")

        # get slice params
        (VS1, VS2, VS3, VS4, VST, VSF) = self.GetParamsForSlice(isVect=True)
        ax_Titles = Manyo.MakeStringVector()
        ax_Units = Manyo.MakeStringVector()
        for i in range(4):
            print("Ax%d = %s" % (i, self.ProjectionCtrl[i][4].text().strip()))
            ax_Titles.push_back(str(self.ProjectionCtrl[i][4].text().strip()))
            ax_Units.push_back(str(self.ProjectionUnitCtrl[i].text().strip()))

        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]))
        print("Units=%s,%s,%s,%s" %
              (ax_Units[0], ax_Units[1], ax_Units[2], ax_Units[3]))

        # open directory dialog
        filepath, filt = QtWidgets.QFileDialog.getSaveFileName(
            self, "Set File to save D4Mat data ...", os.getcwd(), filter='D4Mat.xml (*.xml)')
        if filepath == "":
            return
        # get path
        # filepath = dlg.GetPath()

        if filepath[-4:] != ".xml":
            filepath += ".xml"
        dir_path = str(os.path.dirname(filepath))
        paramfile = str(os.path.basename(filepath))
        st = time.time()
        self.D4MatR.AllocateD4MatOnDisk(
            VS1, VS2, VS3, VS4, ax_Titles, ax_Units, dir_path, paramfile)
        print("---- Cost of time = {}".format(time.time() - st))

    #################################
    def OnConvSPEFiles(self, isSPE=True):
        """
        """
        self.ShowMessage("OnConvSPEFiles")

        """
        #import ana.Reduction.DefaultInstParams as DFI
        #L2 = DFI.Def_L2*1000.0     # [mm]
        #dS = DFI.Def_dS        # [mm]
        hh = Manyo.HeaderBase()
        L2 = 1.0
        dS = 1.0
        runNo = 0
        if self.IsContinuousMethod:
            runNo = self.DataStoreContRot.RunNo
            if self.DataConverter.AddRunInfoToHeader(hh):
                L2 = hh.PutDouble("TypicalL2")
                dS = hh.PutDouble("TypicalDS")
        else:
            for a_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[a_key]
                runNo = int(ex_runs.split(",")[0])
                break
        dOmega = dS/(L2*L2)
        #mask_file = self.DataStoreContRot.MaskFile
        if self.IsContinuousMethod:
            mask_path = self.DataStoreContRot.MaskFile
        else:
            mask_path = self.DataStoreStepByStep.MaskFile
        if mask_path.upper()=="DEFAULT":
            mask_path=PutDefaultMaskFile( int(runNo) )
        elif not os.path.exists( mask_path ):
            inst_dir = mu.UtsusemiEnvGetInstDir()
            if  inst_dir!="":
                mask_path = os.path.join(inst_dir,"ana","xml",mask_file)
                if not os.path.exists( mask_path ):
                    user_dir = mu.UtsusemiEnvGetUserDir()
                    if user_dir=="":
                        mask_path = os.path.join(user_dir,"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 = ""
        """

        target_folder = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Choose Directory to save SPE files ...", os.getcwd())
        if target_folder == "":
            return
        # check selected dir
        if not os.path.exists(target_folder):
            print(self.CommnetHead + "Cannot find such directory, " + target_folder)
            raise

        #
        Temp_NxSpe = 0.0
        if not isSPE:
            isCont = True
            temp = 0.0
            while(isCont):
                temp, result = SetTemperatureNxSPEDialog.get_temperature(self)
                if result:
                    if temp > 0.0:
                        isCont = False
            Temp_NxSpe = temp

        inst_code = mu.UtsusemiEnvGetInstCode()
        if self.IsContinuousMethod:
            # runNo = self.DataStoreContRot.RunNo
            runNoAngleList = self.DataStoreContRot.RunNoAngleList[:]
            runNo = runNoAngleList[0][0]
            # fname_tmp = "%3s%06d_%s" ## %(instCode, runNo, Phi)
            fname_tmp = "{:3s}{:06d}_{:08.3f}"  # %(instCode, runNo, Phi)
            num_data = self.D4MatR.PutSize()
            # labels = self.D4MatR.PutLabelsOfImportedEcm()
            phx_base_name = "%3s%06d" % (inst_code, runNo)
            d4matone = mu.D4MatOne()
            phi_val_key = d4matone.D4MAT2ANGLE

            if isSPE:
                pdg = QtWidgets.QProgressDialog(
                    "Output to SPE files", "Abort", 0, num_data, self)
            else:
                pdg = QtWidgets.QProgressDialog(
                    "Output to nxspe files", "Abort", 0, num_data, self)
            pdg.setWindowModality(QtCore.Qt.WindowModal)
            for i in range(num_data):
                ecm = Manyo.ElementContainerMatrix()
                self.D4MatR.ExportEcmFromStepByStep(ecm, i)
                # fname = fname_tmp%(inst_code,runNo,labels[i])
                phi = ecm.PutHeaderPointer().PutDouble(phi_val_key)
                fname = fname_tmp.format(inst_code, runNo, phi)
                fname = fname.replace(".", "_")
                if isSPE:
                    BC.SaveDataToSPE(ecm, path=target_folder, filename=fname,
                                     phxfile=(phx_base_name + ".phx"), parfile=(phx_base_name + ".par"))
                else:
                    # params = "PSI:{:s},TEMP:{:g},USER:mlfuser".format(label[i],Temp_NxSpe)
                    params = "PSI:{:g},TEMP:{:g},USER:mlfuser".format(
                        phi, Temp_NxSpe)
                    BC.SaveDataToNxspe(ecm, path=target_folder,
                                       filename=fname, params=params)
                del ecm
                pdg.setValue(i)
                if pdg.wasCanceled():
                    pdg.close()
                    return
            pdg.close()
            """
            cond_list = self.DataConverter.PutListOfCounterConditions()
            num_of_cases = self.DataConverter.PutCaseDecoder()._NumOfCases
            runNo = self.DataStoreContRot.RunNo
            instCode = os.environ["UTSUSEMI_INST_CODE"]
            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 = Manyo.ElementContainerMatrix()
                self.DataConverter.SetElementContainerMatrix( ecm, caseId )

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

                if mask_path!="":
                    MSK = Manyo.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()
                URI.dHWCorrect()
                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)
                if isSPE:
                    BC.SaveDataToSPE(ecm, path=target_folder,filename=(fname_tmp%(instCode,runNo,Phi)))
                else:
                    params = "PSI:{:g},TEMP:{:g},USER:mlfuser".format(ex_angle,Temp_NxSpe)
                    BC.SaveDataToNxspe(ecm, path=target_folder,filename=fname,params=params)
            """
        else:  # Step by Step
            ex_runs_list = []
            for gonio_key in self.RunList:
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[gonio_key]
                ex_runs_sp = ex_runs.split(",")
                for a_run in ex_runs_sp:
                    ex_runs_list.append(int(a_run))
            ex_runs_list.sort()
            phx_base_name = "%3s%06d_%06d" % (
                inst_code, ex_runs_list[0], ex_runs_list[-1])

            gonio_list = list(self.RunList.keys())
            gonio_list.sort()
            num_gonio_list = len(gonio_list)
            if isSPE:
                pdg = QtWidgets.QProgressDialog(
                    "Output to SPE files", "Abort", 0, num_gonio_list, self)
            else:
                pdg = QtWidgets.QProgressDialog(
                    "Output to nxspe files", "Abort", 0, num_gonio_list, self)
            pdg.setWindowModality(QtCore.Qt.WindowModal)
            # for gonio_key in self.RunList:
            for i, gonio_key in enumerate(gonio_list):
                ex_mk, ex_runs, ex_angle, ex_protons, ex_ind = self.RunList[gonio_key]
                ecm = Manyo.ElementContainerMatrix()
                self.D4MatR.ExportEcmFromStepByStep(ecm, ex_ind)
                ex_runs_sp = ex_runs.split(",")
                a_run = int(ex_runs_sp[0])
                fname = "%3s%06d" % (inst_code, a_run)
                if isSPE:
                    BC.SaveDataToSPE(ecm, path=target_folder, filename=fname,
                                     phxfile=(phx_base_name + ".phx"), parfile=(phx_base_name + ".par"))
                else:
                    params = "PSI:{:g},TEMP:{:g},USER:mlfuser".format(
                        ex_angle, Temp_NxSpe)
                    BC.SaveDataToNxspe(ecm, path=target_folder,
                                       filename=fname, params=params)
                # fname = "%3s_%s"%(instCode,gonio_key)
                # BC.SaveDataToSPE(ecm, path=target_folder,filename=fname)
                del ecm
                pdg.setValue(i)
                if pdg.wasCanceled():
                    pdg.close()
                    return
            pdg.close()

    #################################
    def OnDumpAllAsText(self):
        """
        """
        self.ShowMessage("OnDumpAllAsText")
        # open directory dialog
        filepath, filt = QtWidgets.QFileDialog.getSaveFileName(
            self, "Set File to save D4Mat data ...", os.getcwd(), filter='text (*.txt)')
        if filepath == "":
            return
        # 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])
        print("VSF=", VSF[0], VSF[1], VSF[2], VSF[3])
        CP = Manyo.CppToPython()
        ax1range = CP.ListToDoubleVector([VS1[0], VS1[1], VS1[2]])
        ax2range = CP.ListToDoubleVector([VS2[0], VS2[1], VS2[2]])
        ax3range = CP.ListToDoubleVector([VS3[0], VS3[1], VS3[2]])
        ax4range = CP.ListToDoubleVector([VS4[0], VS4[1], VS4[2]])
        isAve = True
        print("DumpAsText start...")
        if self.D4MatR.PutSlicedD4MatrixToText(filepath, ax1range, ax2range, ax3range, ax4range, VSF, isAve):
            msg = "D4Mat2Slicer >> DumpAsText suceeded. ({})".format(filepath)
            mu.UtsusemiMessage(msg)
            print(msg)
            pass
        else:
            mu.UtsusemiError("OnDumpAllAsText : Failed.")

    #################################
    def OnSlice3D(self, evt=None):
        """
        """
        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].text().strip()
            if VST[i] == "y":
                flag[1] += 1
                titles_org[1] = self.ProjectionCtrl[i][4].text().strip()
            if VST[i] == "z":
                flag[2] += 1
                titles_org[2] = self.ProjectionCtrl[i][4].text().strip()
            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 with SliceViewer3D
        if USE_SLICEVIEW3D:
            if self.SliceViewer3d is None:
                self.SliceViewer3d = SV.SliceViewer()
            if not self.SliceViewer3d.plot.IsAliveComm():
                del self.SliceViewer3d
                self.SliceViewer3d = SV.SliceViewer()
            if self.SliceViewer3d.setData(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])
        else:
            # if SliceViewer3D is disabled
            # open dialog to save sliced 3D data as mdb file
            filepath, filt = QtWidgets.QFileDialog.getSaveFileName(
                self, "Set File to save D4Mat data ...", os.getcwd(), filter='D4MatSlice3D.mdb (*.mdb)')
            if filepath == "":
                return

            BC.SaveDataToManyoBinary(ecm_ret, path=os.path.dirname(
                filepath), filename=os.path.basename(filepath))
            return


#################################
    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].currentIndex()])
            fold_list.append(float(self.SliceFold[i].text().strip()))

        DiagCond = self.DiagFoldType.currentIndex()
        # print "### DiagCond = ",DiagCond
        foldings = []
        if (DiagCond == 1) or (DiagCond == 2) or (DiagCond == 3):
            foldings.append(float(DiagCond))
            ax_fold = [-1, -1]
            for i, a_cb in enumerate(self.DiagFoldAxesList):
                c_id = a_cb.currentIndex()
                if c_id == 1: # X' is selected.
                    ax_fold[0] = i
                elif c_id == 2: # Y' is selected.
                    ax_fold[1] = i

            if -1 in ax_fold:
                print("Diagonal Folding failed. (X' or Y' is not found.)")
                # return
                foldings.clear()
            else:
                foldings.append(float(ax_fold[0]))
                foldings.append(float(ax_fold[1]))

        fold_list.extend(foldings)

        sliceInfo = []  # [ "type", min, max, width ]
        for id in range(4):
            a_list = [type_list[id]]
            for i in range(3):
                a_list.append(float(self.SliceRange[3 * id + i].text().strip()))
            a_list.append(fold_list[id])
            sliceInfo.append(a_list)

        if isVect:
            VS1 = Manyo.MakeDoubleVector()
            VS2 = Manyo.MakeDoubleVector()
            VS3 = Manyo.MakeDoubleVector()
            VS4 = Manyo.MakeDoubleVector()
            VST = Manyo.MakeStringVector()
            VSF = Manyo.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])
            for val in fold_list:
                VSF.append(val)
            return (VS1, VS2, VS3, VS4, VST, VSF)
        else:
            return sliceInfo

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

        if self.DataConverter is not None:
            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?"

            ret = QtWidgets.QMessageBox().warning(None, u"Warning", msg,
                                                  QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Cancel)
            if ret == QtWidgets.QMessageBox.Cancel:
                self.OnLineModeBtn.setChecked(not isToggleOn)
                return
            self.D4MatR.ResetD4mat()
            del self.DataConverter
            self.DataConverter = None
            if self.IsAutoUpdateMode:
                self.IsAutoUpdateMode = False

        if isToggleOn:
            self.BtnReductionInfo.setEnabled(False)
            self.BtnDRExec.setEnabled(False)
            print("isToggleOn is True")
            self.DataConverter = mu.UtsusemiEventDataMonitorNeunet()
            self.doneOnLineModeFirstPrmSet = False
        else:
            self.BtnReductionInfo.setEnabled(True)
            self.BtnDRExec.setEnabled(True)
            print("isToggleOn is False")
            self.DataConverter = None

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

        self.IsOnLineMode = isToggleOn

    #################################
    def OnAUupdate(self, evt=None):
        """
        """
        # 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
            runNoAngleList = self.DataStoreContRot.RunNoAngleList[:]
            runNo, st_deg = runNoAngleList[0]
            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, self.DataStoreContRot.TimeIndepBack)

            # st_deg = self.DataStoreContRot.AngleStart
            min_deg = self.DataStoreContRot.AngleMin
            max_deg = self.DataStoreContRot.AngleMax
            w_deg = self.DataStoreContRot.AngleStep
            t_start = self.DataStoreContRot.TimeSliceStart
            t_end = self.DataStoreContRot.TimeSliceEnd
            dio = self.DataStoreContRot.TrigNETinfoDIO
            ang_per_enc = self.DataStoreContRot.AngPerEncode
            DU = D4Mat2Utils()
            cfile = DU.MakeCaseInfoFile(
                st_deg, min_deg, max_deg, w_deg, runNo, dio, ang_per_enc)
            self.DataConverter.SetRunNumber(runNo)
            self.DataConverter.SetDataFolder(mu.UtsusemiEnvGetDataDir())
            self.DataConverter.ParameterSet(wfile, dfile, cfile, 1)
            self.DataConverter.AddAllDataModules()
            self.doneOnLineModeFirstPrmSet = True
            self.D4MatR.ResetD4mat()
            self.doneD4MatPrmSet = False

        if self.OnLineModeCkbCtrlList[0].checkState() == QtCore.Qt.Checked:
            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].setEnabled(self.IsReadyProjection)
                self.ShowMessage("--Increment end--")

        if self.OnLineModeCkbCtrlList[1].checkState() == QtCore.Qt.Checked:
            self.OnProjForOnLine()
            """
            runNoAngleList,DRP,LC,UV,VV,VA,RV = self.GetProjectionParam()
            runNo=runNoAngleList[0][0]
            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.DataReductContRot=ExecDataReductionContRot(self,self.lock,True)
            self.ShowMessage("--Projection--")
            self.DataReductContRot.OnStart(self.DataConverter, self.D4MatR,self.DataStoreContRot)
            self.ShowMessage("--Projection end--")
            self.isEnableSlice = True
            """
            if self.OnLineModeCkbCtrlList[2].checkState() == QtCore.Qt.Checked:
                if (isinstance(evt, bool) and evt is True) or evt is None:
                    while(self.DataReductContRot.num_of_updated != self.DataReductContRot.index):
                        time.sleep(0.5)
                    self.SliceContRotData(isRefresh=False)
            else:
                for a_btn in self.ButtonCtrlList[2:]:
                    a_btn.setEnabled(True)
                self.CheckEnableSliceButton()

    #################################

    def OnAUstart(self, evt=None):
        """
        """

        # print( "OnAUstart event" )

        if (self.IsAutoUpdateMode):
            self.ShowMessage("[AutoUpdate]--FINISHED--")
            self.IsAutoUpdateMode = False
            self.OnLineModeBtnCtrlList[0].setEnabled(True)
            self.OnLineModeBtnCtrlList[1].setText("Interval Start")
            self.AUIntervalTimeTxt.setEnabled(True)
        else:
            self.OnLineModeBtnCtrlList[0].setEnabled(False)
            self.OnLineModeBtnCtrlList[1].setText("Stop")
            self.OnAUupdate(True)
            self.IsAutoUpdateMode = True
            self.ShowMessage("[AutoUpdate]--START--")
            update_sec = float(self.AUIntervalTimeTxt.text().strip())
            if (update_sec < 10.0):
                return
            self.AUIntervalTimeTxt.setEnabled(False)

            self.timer_online = QtCore.QTimer(self)
            self.timer_online.timeout.connect(self.OnAutoUpdate)
            self.timer_online.start(int(update_sec) * 1000)

    #################################
    def OnAutoUpdate(self, evt=None):
        """
        """
        if self.IsAutoUpdateMode:
            if self.OnLineModeCkbCtrlList[2].checkState() == QtCore.Qt.Checked:
                if self.DataReductContRot.num_of_updated == self.DataReductContRot.index:
                    self.SliceContRotData(isRefresh=False)

            if self.OnLineModeCkbCtrlList[0].checkState() == QtCore.Qt.Checked:
                if self.DataReductContRot.num_of_updated == self.DataReductContRot.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].setEnabled(self.IsReadyProjection)

                    if self.OnLineModeCkbCtrlList[1].checkState() == QtCore.Qt.Checked:
                        if self.DataReductContRot.num_of_updated == self.DataReductContRot.index:
                            runNoAngleList, DRP, LC, UV, VV, VA, RV, VAT, VAU = self.GetProjectionParam()
                            runNo = runNoAngleList[0][0]
                            self.D4MatR.SetD4MatSampleInfo(LC, UV, VV, RV)
                            self.D4MatR.SetD4MatDataReductionInfo(DRP)
                            self.D4MatR.SetD4MatRunNo(runNo)
                            self.D4MatR.SetD4MatProjectionAxesInfo(VA)

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

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

    #################################
    def OnAUwithProjection(self, evt=None):
        """
        """
        # rint( "OnAUwithProjection event" )
        isEnable = True
        if self.OnLineModeCkbCtrlList[1].isChecked():
            isEnable = False

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

    #################################
    def OnAUwithSlice(self, evt=None):
        """
        """
        # print( "OnAUwithSlice event" )
        isEnable = True
        if self.OnLineModeCkbCtrlList[2].isChecked():
            isEnable = False
        for a_item in self.SliceAxis:
            a_item.setEnabled(isEnable)
        for a_item in self.SliceRange:
            a_item.setEnabled(isEnable)
        for a_item in self.SliceFold:
            a_item.setEnabled(isEnable)
        for i in range(2, 8):
            self.ButtonCtrlList[i].setEnabled(isEnable)
        self.DiagFoldType.setEnabled(isEnable)
        self.isEnableSlice = isEnable
        self.CheckEnableSliceButton()

    #########################################
    def OnChoiceRotateAxes2(self, evt=None):
        """
        """
        if self.chrotax1.currentIndex() == 0:
            self.SampleInfoCtrl[12].setEnabled(False)
            self.chrotax2.setEnabled(False)
            self.SampleInfoCtrl[13].setEnabled(False)
            self.chrotax3.setEnabled(False)
            self.SampleInfoCtrl[14].setEnabled(False)
        else:
            self.SampleInfoCtrl[12].setEnabled(True)
            self.chrotax2.setEnabled(True)
            if self.chrotax2.currentIndex() == 0:
                self.SampleInfoCtrl[13].setEnabled(False)
                self.chrotax3.setEnabled(False)
                self.SampleInfoCtrl[14].setEnabled(False)
            else:
                self.SampleInfoCtrl[13].setEnabled(True)
                self.chrotax3.setEnabled(True)
                if self.chrotax3.currentIndex() == 0:
                    self.SampleInfoCtrl[14].setEnabled(False)
                else:
                    self.SampleInfoCtrl[14].setEnabled(True)

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

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

        else:
            if (self.chrotax1.currentIndex() == 0) or (self.chrotax2.currentIndex() == 0) or (bt.currentIndex() == 0):
                self.SampleInfoCtrl[14].setEnabled(False)
            else:
                self.SampleInfoCtrl[14].setEnabled(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, param_TimeIndepBack="None"):
        """
        """
        hh = mu.UtsusemiGetNeunetHistogram()
        hh.SetRunNo(runNo)
        hh.SetConversionParameter(params)
        print("D4Mat2Utils::MakeTempInfoFiles >> st_Params=%s" % params)
        hh.SetDetParam("PSD,TRIGNET")

        # Set BackGround Info Parameters
        # repalce keys "TOF:" and "TIMEINDEP:" with "TIMEDEP:"
        param_TimeIndepBack = param_TimeIndepBack.upper()
        param_TimeIndepBack = param_TimeIndepBack.replace("TOF:", "TIMEDEP:")
        param_TimeIndepBack = param_TimeIndepBack.replace("TIMEINDEP:", "TIMEDEP:")
        if param_TimeIndepBack.upper().find("TIMEDEP:") < 0:
            pass
        else:
            ind = param_TimeIndepBack.upper().find("TIMEDEP:")
            ind1 = param_TimeIndepBack.upper().find("(")
            ind2 = param_TimeIndepBack.upper().find(")")
            if ind1 < 0:
                param = param_TimeIndepBack[(ind + 8):]
                if not hh.SetTimeDependBackGroundInfo(param):
                    del hh
                    raise UserWarning(
                        " param_TimeIndepBack >>> TimeIndep parameter is invalid.(" + param + ")")
            else:
                del hh
                raise UserWarning(
                    " param_TimeIndepBack >>> TimeIndep parameter is invalid.(" + param + ")")

        tmp_files = hh.MakeTempInfoFiles()
        del hh
        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 is None:
            return None

        UGH = mu.UtsusemiGetNeunetHistogram()

        (flag, param) = p_dic[self.HSTKEY_AnaMode]
        if flag:
            ana_mode_list = param.split(",")
            if len(ana_mode_list) == 1:
                UGH.SetRunNo(runNo, ana_mode_list[0])
            elif len(ana_mode_list) == 3:
                pfiles = "%s,%s" % (
                    ana_mode_list[1].strip(), ana_mode_list[2].strip())
                if pfiles == "-,-":
                    UGH.SetRunNo(runNo, ana_mode_list[0])
                else:
                    UGH.SetRunNo(runNo, pfiles[0], pfiles[1], ana_mode_list[0])
        else:
            UGH.SetRunNo(runNo)

        (flag, param) = p_dic[self.HSTKEY_HistParam]
        UGH.SetConversionParameter(param)

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

        (flag, param) = p_dic[self.HSTKEY_CaseInfo]
        if flag:
            UGH.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):]
                UGH.SetTimeDependBackGroundInfo(param)
        (flag, param) = p_dic[self.HSTKEY_TofShift]
        if flag:
            UGH.SetTofShiftInfo(param)
        (flag, param) = p_dic[self.HSTKEY_Options]
        if flag:
            options_list = param.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 = UGH.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, min_deg, max_deg, step_deg, runNo, dio, ang_per_enc=0.0):
        """
        """
        print("D4Mat2Utils::MakeTempInfoFiles")

        fname = "CaseInfo_%s_%06d_%06d.xml" % (
            os.environ["USER"], runNo, os.getpid())
        user_dir = mu.UtsusemiEnvGetUserDir()
        if user_dir != "":
            ss = os.path.join(user_dir, "ana", "xml", fname)
        else:
            ss = os.path.join(os.environ["HOME"], "ana", "xml", fname)

        if ang_per_enc == 0.0:
            inst_code = mu.UtsusemiEnvGetInstCode()
            D4Mat2 = mu.UtsusemiD4Matrix2()
            XP = D4Mat2.PutTreatD4Mat2XmlParams()
            if inst_code == "SIK":
                #ang_per_enc = XP.deviceEncodeDic.Put("BL01-TL")
                ang_per_enc = XP.PutDeviceEncode("BL01-TL")
            elif inst_code == "AMR":
                #ang_per_enc = XP.deviceEncodeDic.Put("BL14-TL")
                ang_per_enc = XP.PutDeviceEncode("BL14-TL")

        template = '''<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE CaseInfo 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' % (
            min_deg, max_deg, step_deg)
        template += '''
        </conditions>
    </counter>
    </counters>
</caseInfo>
'''
        template = '''<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE CaseInfo SYSTEM "CaseInfo.dtd" >
<caseInfo>
    <caseAmbiguity>1</caseAmbiguity>
    <filters/>
    <counters n="1">
    <counter i="0" type="ABC">
        <signal n="1">
            <trignet i="0" index="0" type="LADC1" io="DIO%dR" />
        </signal>
        <conversionVal>%g</conversionVal>
''' % (dio, ang_per_enc)
        template += '        <originVal unit="Degree">%f</originVal>\n' % (
            start_deg)
        template += '        <conditions type="2" >\n'
        template += '            <cond>%f,%f,%f</cond>\n' % (
            min_deg, max_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 is None:
            # 2Dプロッタフレームクローズイベントのリスナー登録
            self.ifi.AddListner('u2dclosed', self.OnNotify2DClose)
            # self.d2 = D2Vis.MapD2Frame(self.frame , map, self.pno, self.code)
            self.d2 = D2Vis.M2PlotPlus(self.frame, None, self.pno)
        # else:
            # データ変更
        #    if isRefresh:
        #        self.ifi.NotifyEvent(self, "changedata", eca)
        #    else:
        #        self.ifi.NotifyEvent(self, "updatedata", eca)
        self.ifi.NotifyEvent(self, "changedata", eca)
        self.ifi.NotifyEvent(
            self, "showdata", (labels[5], labels[6], "-", 0.0, 0.0))
        self.ifi.NotifyEvent(self, "settitles", (labels[0], labels[1], True))
        self.ifi.NotifyEvent(self, "setlabels", (labels[2], labels[3]))

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

        self.plotNow = (eca, labels[0], labels[1])

    #########################################

    def OnNotify2DClose(self, *args):
        """
        2Dプロッタクローズイベント受信処理
        @param evt イベント
        @retval 無し
        """
        # self.d2 = None
        self.plotNow = None
        if self.d2 is not None:
            del self.d2
            self.d2 = None
        self.ifi.InitIF()

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


#######################################
#  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)
    # Hi-resolution Display for windows
    if PYSIDEVER != 6:
        if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):
            QtWidgets.QApplication.setAttribute(
                QtCore.Qt.AA_EnableHighDpiScaling, True)
    app = QtWidgets.QApplication(sys.argv)
    # Set Default Font Size to (default 14)
    deffont = app.font()
    if "UTSUSEMI_DEFAULT_FONTSIZE" in os.environ:
        deffontsize = int(os.environ["UTSUSEMI_DEFAULT_FONTSIZE"])
        deffont.setPointSize(deffontsize)
    else:
        deffont.setPointSize(10)
    app.setFont(deffont)
    app.setWindowIcon(QtGui.QIcon(os.path.join(
        os.environ["UTSUSEMI_BASE_DIR"], "ana", "Reduction", "ICON_Utsusemi4.png")))

    splash_path = os.path.join(
        os.environ["UTSUSEMI_BASE_DIR"], "ana", "Reduction", "LOGO_utsusemi4_c_box.png")
    splash = None
    if os.path.exists(splash_path):
        # splash = UtsusemiSplashScreen(splash_path)
        # splash.Show()
        pixmap = QtGui.QPixmap(splash_path)
        splash = QtWidgets.QSplashScreen(
            pixmap, QtCore.Qt.WindowStaysOnTopHint)
        splash.setMask(pixmap.mask())
        splash.show()
        splash.showMessage("Now Launching")

        app.processEvents()
        time.sleep(1)

    frame = D4Mat2Slicer(None)
    if splash is not None:
        splash.finish(frame)
    if PYSIDEVER == 6:
        sys.exit(app.exec())
    else:
        sys.exit(app.exec_())
    # app.MainLoop()
