#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
#import time,sys,os,math,glob,datetime,re,urllib,httplib,socket
import time,sys,os,math,glob,datetime,re,urllib,socket
import Manyo as mm
import Manyo.Utsusemi as mu
import Manyo.DNA as md

import utsusemi.ana.Reduction.BaseCommandsInEla as BaseCom
import utsusemi.DNA.ana.Reduction.PeakFit as PF
import utsusemi.DNA.ana.Reduction.SearchPathDNA as SPD
import shutil
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

from utsusemi.DNA.ana.Reduction.DefaultInstParams import *
socket.setdefaulttimeout(1)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHW(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=True,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,UseFastChopper,1,0,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHW333(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=True,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,UseFastChopper,2,0,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHW311(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=True,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,UseFastChopper,3,0,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHWTrignet(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",tofSource="0.0/400.0",useTrignet=1,ChopperFrequency=225.0,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,True,1,useTrignet,tofSource,ChopperFrequency,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHW333Trignet(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",tofSource="0.0/400.0",useTrignet=1,ChopperFrequency=225.0,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,True,2,useTrignet,tofSource,ChopperFrequency,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHWnoTrignet(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",tofSource="0.0/400.0",useTrignet=4,ChopperFrequency=225.0,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,True,1,useTrignet,tofSource,ChopperFrequency,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------
def GetHistogramHW333noTrignet(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",tofSource="0.0/400.0",useTrignet=4,ChopperFrequency=225.0,tofOffsetFile="",isHistogram=False,WIoutput=None):
    return GetHistogramHWBase(runNo,HwParam,LambdaParam,t0_offset,useT0ModCorr,TimeParam,True,2,useTrignet,tofSource,ChopperFrequency,tofOffsetFile=tofOffsetFile,isHistogram=isHistogram,WIoutput=WIoutput)
#------------------------------------------------------------------------------------------------------------

def GetHistogramHWBase(runNo=197,HwParam="0.01/-1.00/1.00",LambdaParam="6.26/3.34",t0_offset="0.0",useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=True,LaticeParam=1,useTrignet=False,tofSource="0.0/400.0",ChopperFrequency=225.0,tofOffsetFile="",isHistogram=False,WIoutput=None):
    #p 1      ,p2         ,p3             ,p4           ,p5                ,p6           ,p7
    #runNo=189,HwParam=" ",LambdaParam=" ",t0_offset=0.0,useT0ModCorr=False,TimeParam=" ",UseFastChopper=True

    #useT0ModCorr   = False #@@@@@@@@@@
    #t0_offset      = 0.0   #@@@@@@@@@@
    #useT0ModCorr   = False #@@@@@@@@@@
    #useFaseChopper = True  #@@@@@@@@@@
    #hw_start       =-1.00  #@@@@@@@@@@
    #hw_end         = 1.00  #@@@@@@@@@@
    #hw_delta       = 0.01  #@@@@@@@@@@
    #Lambda_center  = 6.26  #@@@@@@@@@@
    #delta_Lambda   = 3.34  #@@@@@@@@@@

    #startTime      =-1     #@@@@@@@@@@
    #endTime        =-1     #@@@@@@@@@@

    #t0_offset_from_wf = 0.00  #@@@@@@@
    #----Lambda Param----#
    if "," in LambdaParam:
        lambdaParamList = LambdaParam.split(",")
    elif "/" in LambdaParam:
        lambdaParamList = LambdaParam.split("/")
    else:
        lambdaParamList = []
    try:
        Lambda_center = float(lambdaParamList[0])
        delta_Lambda = float(lambdaParamList[1])
    except:
        print("Lambda Param is invalid. [Lambda_center,delta_Lambda] = [5.66,3.66]")
        Lambda_center = 5.66
        delta_Lambda  = 3.66

    #----T0 offset Param----#
    Ecenter        = _LambdaToEnergy(Lambda_center)
    t0_offset_calc = _psdGetT0OffsetCalc(useT0ModCorr,Ecenter)

    if type(t0_offset)!=str:
        t0_offset = str(t0_offset)
    try:
        if "," in t0_offset:
            tof_offset = float(t0_offset.split(",")[0])
        elif  "/" in t0_offset:
            tof_offset = float(t0_offset.split("/")[0])
        else:
            tof_offset = float(t0_offset)
    except:
        tof_offset = 0

    t0_offset_from_wf = - (tof_offset + t0_offset_calc)

    #----L1 Param----#
    L1=_psdGetL1(UseFastChopper,runNo,energy=True)
    dpath = _getDetectorInfoPath(runNo)
    _writeL1Param(L1,dpath)

    #----Latice Param----#
    LaticeSpace=_psdGetLaticeSpace(LaticeParam)

    #----HW Param----#
    if "," in HwParam:
        HwParamList = HwParam.split(",")
    elif "/" in HwParam:
        HwParamList = HwParam.split("/")
    else:
        HwParamList=[]
    try:
        if len(HwParamList)==3:
            dHW    = float(HwParamList[0])
            hw_min = float(HwParamList[1])
            hw_max = float(HwParamList[2])
            HwParamListFloat = [hw_min, hw_max, dHW]
        elif len(HwParamList)>3:
            HwParamListFloat = [float(val) for val in HwParamList]
        else:
            print("HW Param is invalid. [dHW,hw_min,hw_max] = [0.002,-1.0,1.0]")
            dHW    = 0.002
            hw_min = -1.0
            hw_max = 1.0
            HwParamListFloat = [hw_min,hw_max,dHW]
    except:
        print("HW Param is invalid. [dHW,hw_min,hw_max] = [0.002,-1.0,1.0]")
        dHW    = 0.002
        hw_min = -1.0
        hw_max = 1.0
        HwParamListFloat = [hw_min,hw_max,dHW]

    #----Time Param----#
    if "," in TimeParam:
        TimeParamList = TimeParam.split(",")
    elif "/" in TimeParam:
        TimeParamList = TimeParam.split("/")
    else:
        TimeParamList=[]
    try:
        startTime = float(TimeParamList[0])
        endTime   = float(TimeParamList[1])
    except:
        print("Time Param is invalid. [startTime,endTime] = [-1.0,-1.0]")
        startTime = -1.0
        endTime   = -1.0

    #----Chopper Frequency Param----#
    try:
        ChopperFrequency=float(ChopperFrequency)
    except:
        ChopperFrequency=225.0

    #----Print Param----#
    if len(HwParamList)==3:
        print("HwParam")
        print("dHW = ",dHW)
        print("hw_min = ",hw_min)
        print("hw_max = ",hw_max)
    print("LambdaParam")
    print("LambdaCenter = ",Lambda_center)
    print("deltaLambda = ",delta_Lambda)
    print("TimeParam")
    print("startTime = ",startTime)
    print("endTime = ",endTime)
    print("L1[m]= ",L1)

    if len(HwParamList)==3:
        if useTrignet>0:
            Params = HwParamListFloat + [Lambda_center,delta_Lambda,0.0, LaticeSpace, L1]
        else:
            Params = HwParamListFloat + [Lambda_center,delta_Lambda,t0_offset_from_wf, LaticeSpace, L1]
    else:
        if useTrignet>0:
            Params = [Lambda_center,delta_Lambda,0.0, LaticeSpace, L1] + HwParamListFloat
        else:
            Params = [Lambda_center,delta_Lambda,t0_offset_from_wf, LaticeSpace, L1] + HwParamListFloat

    DAT=GetHistogramHWROOT(runNo=runNo, params=Params, startTime=startTime, endTime=endTime,
                           useTrignet=useTrignet, t0_offset=t0_offset, tofOffsetFile=tofOffsetFile,
                           tofSource=tofSource, ChopperFrequency=ChopperFrequency,isHistogram=isHistogram,WIoutput=WIoutput)
    return DAT
#------------------------------------------------------------------------------------------------------------
def GetHistogramHWROOT(runNo=197,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,
                       NumOfPixel=Def_NumOfPixel,params=[],startTime=-1,endTime=-1,
                       useTrignet=False,t0_offset="0.0",tofOffsetFile="",tofSource="0.0/400.0",ChopperFrequency=225.0,isHistogram=False,WIoutput=None):
    """
    Load EventData and convert to histogram.
    GetHistogram(runNo,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,
                  NumOfPixel=Def_NumOfPixel)
    @param runNo    (int) Run Number
    @param paraFlag (int) using parallel methods : 1, single methods : 0
    @param startTOF (double) top TOF value to be selected
    @param endTOF   (double) end TOF value to be selected
    @param binTOF   (double) bin width of TOF
    @param startPSD (int) first PSD ID
    @param endPSD   (int) final PSD ID
    @param NumOfPixel  (int) the number of pixels on one PSD
    @param envFile  (string) Environ file for event data to histogram
    @retval DAT     (ElementContainerMatrix)
    """

    """
    [20141027 TY]
    t0data_dir = os.path.join(os.environ["HOME"],"ana","tmp")
    for filepath in glob.glob(os.path.join(t0data_dir,'*.t0b')):
        print "Delete >> "+filepath
        os.remove(filepath)
    """
    T0bfileCheck(runNo, "uPSD") #[20141027 TY Add]
    if useTrignet:
        T0bfileCheck(runNo,"TRIGNET")
    #spectname=os.environ["UTSUSEMI_SYS_NAME"]
    spectname=mu.UtsusemiEnvGetInstCode()
    if NumOfPixel!=-1:
        if len(Def_NumOfPixels)!=0:
            if not NumOfPixel in Def_NumOfPixels:
                print("Pixel No is invalid. The default value %d is set." % (Def_NumOfPixels[0]))
                NumOfPixel = Def_NumOfPixels[0]

    import utsusemi.DNA.ana.Reduction.Histogram as HH
    if len(params)==8:
        return HH.GetHistogramOfConv(runNo, 27, params, [startPSD,endPSD], NumOfPixel,
                                     [startTime, endTime],DetType="uPSD", useTrignet=useTrignet,
                                     t0_offset=t0_offset, tofSource=tofSource, tofOffsetFile=tofOffsetFile,
                                     ChopperFrequency=ChopperFrequency,isHistogram=isHistogram,WIoutput=WIoutput)
    else:
        return HH.GetHistogramOfConv(runNo, 28, params, [startPSD,endPSD], NumOfPixel,
                                     [startTime, endTime],DetType="uPSD", useTrignet=useTrignet,
                                     t0_offset=t0_offset, tofSource=tofSource, tofOffsetFile=tofOffsetFile,
                                     ChopperFrequency=ChopperFrequency,isHistogram=isHistogram,WIoutput=WIoutput)

#------------------------------------------------------------------------------------------------------------
def GetAnalysisParameter():
    import utsusemi.DNA.ana.Reduction.Histogram as HH
    params=[-0.060000,0.060000,0.000500,6.321000,4.150000,-12325.000000,3.134600,34275.000000]
    return HH.GetAnalysisParameter(params)

#------------------------------------------------------------------------------------------------------------
def GetHistogram(runNo=197,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,NumOfPixel=Def_NumOfPixel):
    """
    Load EventData and convert to histogram.
    GetHistogram(runNo,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,
                  NumOfPixel=Def_NumOfPixel)
    @param runNo    (int) Run Number
    @param paraFlag (int) using parallel methods : 1, single methods : 0
    @param startTOF (double) top TOF value to be selected
    @param endTOF   (double) end TOF value to be selected
    @param binTOF   (double) bin width of TOF
    @param startPSD (int) first PSD ID
    @param endPSD   (int) final PSD ID
    @param NumOfPixel  (int) the number of pixels on one PSD
    @param envFile  (string) Environ file for event data to histogram
    @retval DAT     (ElementContainerMatrix)
    """
    t0data_dir = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp")
    #for filepath in glob.glob(os.path.join(t0data_dir,'*.t0b')):
    #    print "Delete >> "+filepath
    #    os.remove(filepath)

    #spectname=os.environ["UTSUSEMI_SYS_NAME"]
    spectname=mu.UtsusemiEnvGetInstCode()
    if NumOfPixel!=-1:
        if len(Def_NumOfPixels)!=0:
            if not NumOfPixel in Def_NumOfPixels:
                print("Pixel No is invalid. The default value %d is set." % (Def_NumOfPixels[0]))
                NumOfPixel = Def_NumOfPixels[0]

    detectFile = _getDetectorInfoPath(runNo) #[inamura 170615]
    import utsusemi.DNA.ana.Reduction.Histogram as HH
    return HH.GetHistogramOfConv(runNo,2,[startTOF,endTOF,binTOF],[startPSD,endPSD],NumOfPixel,DetType="uPSD")
#------------------------------------------------------------------------------------------------------------
def GetHistogramMon(runNo=197,useEiConv=True, LambdaParam="7.66/6.00", t0_offset="0.0", background=0.0,useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=True,UseTrignet=0,tofSource="0.0/400.0",ChopperFrequency=225.0,isHistogram=False,monType=""):
    """
    Load EventData of monitor and convert to histogram.
    GetHistogramMon(runNo=197,useEiConv=True, LambdaParam="7.66/6.00",
                    t0_offset="0.0", background=0.0,useT0ModCorr=False,
                    TimeParam="-1.0/-1.0",UseFastChopper=True,UseTrignet=0,
                    tofSource="0.0/400.0",ChopperFrequency=225.0,isHistogram=False,
                    monType=""
                   )

    @param runNo    (int) Run Number
    @param useEiConv (bool)
    @param LambdaParam (string)
    @param t0_offset (string)
    @param background (float)
    @param useT0ModCorr (bool)
    @param TimeParam (string) "<start>/<end>"
    @param UseFastChopper (bool)
    @param UseTrignet (int)
    @param tofSource (string)
    @param ChopperFrequency (float)
    @param isHistogram (bool)
    @param monType (str)
    @retval (ElementContainer)
    """

    #----Lambda Param----#
    if "," in LambdaParam:
        lambdaParamList = LambdaParam.split(",")
    elif "/" in LambdaParam:
        lambdaParamList = LambdaParam.split("/")
    else:
        lambdaParamList = []
    try:
        Lambda_center = float(lambdaParamList[0])
        delta_Lambda = float(lambdaParamList[1])
    except:
        print("Lambda Param is invalid. [Lambda_center,delta_Lambda] = [6.321,3.000]")
        Lambda_center = 6.321
        delta_Lambda  = 3.000

    #----Time Param----#
    if "," in TimeParam:
        TimeParamList = TimeParam.split(",")
    elif "/" in TimeParam:
        TimeParamList = TimeParam.split("/")
    else:
        TimeParamList=[]
    try:
        startTime = float(TimeParamList[0])
        endTime   = float(TimeParamList[1])
    except:
        print("Time Param is invalid. [startTime,endTime] = [-1.0,-1.0]")
        startTime = -1.0
        endTime   = -1.0

    #----Chopper Frequency Param----#
    try:
        ChopperFrequency=float(ChopperFrequency)
    except:
        ChopperFrequency=225.0

    #------------------------------------------------------------
    Lambda_min = Lambda_center - delta_Lambda*0.5
    Lambda_max = Lambda_center + delta_Lambda*0.5
    Lambda_center = Lambda_center

    Emin    = _LambdaToEnergy(Lambda_max)
    Ecenter = _LambdaToEnergy(Lambda_center)
    Emax    = _LambdaToEnergy(Lambda_min)

    #------------------------------------------------------------
    print("Lambda_min \t= %.4e"%(Lambda_min))
    print("Lambda_center \t= %.4e"%(Lambda_center))
    print("Lambda_max \t= %.4e"%(Lambda_max))
    print("E_min \t \t= %.4f"%(Emin))
    print("E_center \t= %.4f"%(Ecenter))
    print("E_max \t \t= %.4f"%(Emax))
    #------------------------------------------------------------

    t0_offset_calc = _moniGetT0OffsetCalc(useT0ModCorr,Ecenter)
    #------------------------------------------------------------
    if UseFastChopper>0:
        tof_offset=0
    else:
        try:
            if "," in t0_offset:
                tof_offset = -1.0*float(t0_offset.split(",")[0])
            elif  "/" in t0_offset:
                tof_offset = -1.0*float(t0_offset.split("/")[0])
            else:
                tof_offset = -1.0*float(t0_offset)

        except:
            tof_offset = 0
    #t0_offset = -1.0 * t0_offset #TY Add[141204]
    #------------------------------------------------------------

    #[inamura 220525] Arranged to use monitor position at sample
    if monType == "" or monType.upper() == "N2MON":
        L1 = _moniGetL1(UseFastChopper,runNo)
    elif monType.upper() == "SMPMON":
        L1 = _moniGetL1AtSmp(UseFastChopper,runNo)
    elif monType.upper() == "VANMON":
        L1 = _moniGetL1Van(UseFastChopper,runNo)
    else:
        raise UserWarning("GetHistogramMon >> argument monType is invalid. ({})".format(monType))

    dpath = _getDetectorInfoPath(runNo)
    print("#[inamura 221213] L1={}".format(L1))
    #L1 = L1*1000.0 ## [m]->[mm] [inamura 141201]
    _writeL1Param(L1,dpath)

    boundaryInfo = _moniGetBoundaryInfo(Emin,Emax,Ecenter,L1)
    boundary_min,boundary_max,frameNo,boundary = boundaryInfo
    binInfo = _moniGetBinInfo(boundaryInfo,useEiConv,tof_offset,t0_offset_calc)
    tofBinType,binParams,tof_offset = binInfo
    #------------------------------------------------------------

    if UseFastChopper>0:
        DAT = GetHistogramMonBase(runNo,0,binParams[0],binParams[1],binParams[2],-1,-1,0,tofBinType,startTime,endTime,frameNo,boundary,UseTrignet,t0_offset,Lambda_center,delta_Lambda,tofSource,ChopperFrequency,isHistogram=isHistogram,monType=monType)
    else:
        #tofBinType=2
        #binParams=[0,120000,10]

        #tofBinType=21
        #binParams=[0.01,10,0.01]
        DAT = GetHistogramMonBase(runNo,0,binParams[0],binParams[1],binParams[2],-1,-1,1,tofBinType,startTime,endTime,frameNo,boundary,UseTrignet,str(tof_offset),Lambda_center,delta_Lambda,tofSource,ChopperFrequency,isHistogram=isHistogram,monType=monType)

    print (DAT.PutHeader().Dump())
    print ("#-----------")
    print (DAT.PutTableSize())
    print ("#-----------")
    print (DAT.Put(0).Put(0).Dump())
    print ("#-----------")
    print (DAT.Put(1).Put(0).Dump())
    print ("#-----------")
    print (DAT.Put(1).PutTableSize())
    print ("#-----------")
    if DAT.PutSize() > 5:
        print (DAT.Put(5).Put(0).Dump())
    if monType.upper() == "SMPMON":
        ec  = DAT.Put(1).Put(0)
        ech = DAT.Put(1).Put(0).PutHeader()
    elif monType.upper() == "VANMON":
        ec  = DAT.Put(1).Put(0)
        ech = DAT.Put(1).Put(0).PutHeader()
    elif (runNo >= 24375):
        ec  = DAT.Put(5).Put(0)
        ech = DAT.Put(5).Put(0).PutHeader()
    else:
        ec  = DAT.Put(0).Put(0)
        ech = DAT.Put(0).Put(0).PutHeader()
    #------------------------------------------------------------
    ecOut=_moniBackgroundSubstraction(ec,ech,background,L1,useEiConv)

    ecm_hh = DAT.PutHeader()
    if ecm_hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER)!=0:
        ecOut.AddToHeader( mu.UTSUSEMI_KEY_HEAD_RUNNUMBER, ecm_hh.PutString(mu.UTSUSEMI_KEY_HEAD_RUNNUMBER) )
    if ecm_hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT)!=0:
        ecOut.AddToHeader( mu.UTSUSEMI_KEY_HEAD_INSTRUMENT, ecm_hh.PutString(mu.UTSUSEMI_KEY_HEAD_INSTRUMENT) )
    if ecm_hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_MEASPERIOD)!=0:
        ecOut.AddToHeader( mu.UTSUSEMI_KEY_HEAD_MEASPERIOD, ecm_hh.PutDoubleVector(mu.UTSUSEMI_KEY_HEAD_MEASPERIOD) )
    if ecm_hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_KICKERCOUNT)!=0:
        ecOut.AddToHeader( mu.UTSUSEMI_KEY_HEAD_KICKERCOUNT, ecm_hh.PutInt4(mu.UTSUSEMI_KEY_HEAD_KICKERCOUNT) )
    if ecm_hh.CheckKey(mu.UTSUSEMI_KEY_HEAD_DATAPROCESSED)!=0:
        ecOut.AddToHeader( mu.UTSUSEMI_KEY_HEAD_DATAPROCESSED, ecm_hh.PutStringVector(mu.UTSUSEMI_KEY_HEAD_DATAPROCESSED) )

    return ecOut
    #return ec
#------------------------------------------------------------------------------------------------------------
def GetHistogramMonBase(runNo=197,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,NumOfPixel=4,tofBinType=2,startTime=-1,endTime=-1,frameNo=0,boundary=0.0,useTrignet=0,t0_offset="0.0",Lambda_center=6.321,delta_Lambda=3.0,tofSource="0.0/400.0",ChopperFrequency=255.0,isHistogram=False,monType=""):
    """
    Load EventData and convert to histogram.
    GetHistogram(runNo,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,
                  NumOfPixel=Def_NumOfPixel)
    @param runNo    (int) Run Number
    @param paraFlag (int) using parallel methods : 1, single methods : 0
    @param startTOF (double) top TOF value to be selected
    @param endTOF   (double) end TOF value to be selected
    @param binTOF   (double) bin width of TOF
    @param startPSD (int) first PSD ID
    @param endPSD   (int) final PSD ID
    @param NumOfPixel  (int) the number of pixels on one PSD
    @param envFile  (string) Environ file for event data to histogram
    @retval DAT     (ElementContainerMatrix)
    """
    DNA_MONI_TYPE = ["N2MON", "SMPMON", "VANMON"]
    det_type = "N2MON"
    if monType.upper() in DNA_MONI_TYPE:
        det_type = monType.upper()
    elif monType == "":
        pass
    else:
        raise UserWarning("Argument of GetHistogramMonBase monType is invalid ({})".format(monType.upper()))
    """
    [20141027 TY]
    t0data_dir = os.path.join(os.environ["HOME"],"ana","tmp")
    for filepath in glob.glob(os.path.join(t0data_dir,'*.t0b')):
        print "Delete >> "+filepath
        os.remove(filepath)
    """
    T0bfileCheck(runNo, "N2MON") #[20141027 TY Add]
    if useTrignet:
        T0bfileCheck(runNo,"TRIGNET")

    #spectname=os.environ["UTSUSEMI_SYS_NAME"]
    spectname=mu.UtsusemiEnvGetInstCode()
    if NumOfPixel!=-1:
        if len(Def_NumOfPixels)!=0:
            if not NumOfPixel in Def_NumOfPixels:
                print("Pixel No is invalid. The default value %d is set." % (Def_NumOfPixels[0]))
                NumOfPixel = Def_NumOfPixels[0]
    import utsusemi.DNA.ana.Reduction.Histogram as HH

    DAT = HH.GetHistogramOfConv(runNo,tofBinType,[startTOF,endTOF,binTOF,Lambda_center,delta_Lambda],[startPSD,endPSD],
                                 NumOfPixel,[startTime,endTime],[frameNo,boundary],DetType=det_type,useTrignet=useTrignet,t0_offset=t0_offset,tofSource=tofSource,ChopperFrequency=ChopperFrequency,isHistogram=isHistogram)
    #DAT = HH.GetHistogramOfConv(runNo,tofBinType,[startTOF,endTOF,binTOF,Lambda_center,delta_Lambda],[startPSD,endPSD],
    #                             NumOfPixel,[startTime,endTime],[frameNo,boundary],DetType="N2MON",useTrignet=useTrignet,t0_offset=t0_offset,tofSource=tofSource,ChopperFrequency=ChopperFrequency,isHistogram=isHistogram)
    #DAT = HH.GetHistogramOfConv(runNo,tofBinType,[startTOF,endTOF,binTOF],[startPSD,endPSD],
    #                            NumOfPixel,[startTime,endTime],[frameNo,boundary],DetType="N2MON",useTrignet=useTrignet,t0_offset=t0_offset)
    #<--[inamura 141201]
    return DAT
#------------------------------------------------------------------------------------------------------------
def _writeParam(val,dpath,params,att="",i=0):
    if dpath!="":
        headStr=""
        head=open(dpath)
        l=head.readline()
        if l[:2]=="<?":headStr+=l
        l=head.readline()
        if l[:2]=="<!":headStr+=l

        fd = open(dpath,'rb')
        dom=ElementTree(file=fd)
        fd.close()

        ele = dom.getroot()
        for param in params:
            if param==params[-1]:
                ele = ele.findall(param)
            else:
                ele = ele.find(param)
        valStr=str(val)

        if att=="":
            ele[i].text=valStr
        else:
            ele[i].set(att,valStr)
        dom.write(dpath)

        allline=open(dpath,"r").read()

        f = open(dpath,"w")
        f.write(headStr)
        for line in allline:f.write(line)
        f.close()
#------------------------------------------------------------------------------------------------------------
def _readParam(dpath,params,att="",i=0):
    if dpath!="":
        fd = open(dpath,'rb')
        dom=ElementTree(file=fd)
        fd.close()

        ele = dom.getroot()
        for param in params:
            if param==params[-1]:
                ele = ele.findall(param)
            else:
                ele = ele.find(param)

        if att=="":
            return ele[i].text
        else:
            return ele[i].get(att)
#------------------------------------------------------------------------------------------------------------
def _LambdaToEnergy(Lambda):
    MASS_NEUTRON=1.674928e-27
    HBAR    = 1.054571596e-34
    E = 2.0*math.pi*math.pi*(HBAR/(Lambda*1e-10))*(HBAR/(Lambda*1e-10))/MASS_NEUTRON*0.624*1e22
    return E
#------------------------------------------------------------------------------------------------------------
def _getDetectorInfoPath(runNo):
    envFile="environ_ana.xml"
    ana_env = mu.UtsusemiAnaEnvironReader(envFile)
    param_files = ana_env.PutParamFiles(runNo)

    #dpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",param_files[1])
    dpath = mu.FindParamFilePath(param_files[1])
    if not os.path.exists(dpath):
        print("Can not read file :"+param_files[1])
        return ""
    else:
        # 20151202 start
        fname  = param_files[1][:-4]
        footer = param_files[1][-4:]
        pid = str(os.getpid())
        #copypath=os.path.join(os.environ["HOME"],"ana","xml",fname+"_"+pid+footer)
        copypath=os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",fname+"_"+pid+footer)
        shutil.copy(dpath,copypath)
        # 20151202  end
        return copypath
#------------------------------------------------------------------------------------------------------------
def _writeL1Param(L1,dpath):
    if dpath!="":
        fd = open(dpath,'rb')
        dom=ElementTree(file=fd)
        fd.close()

        root_ele = dom.getroot()
        inst_ele = root_ele.find("instrumentInfo")
        L1Str=str(L1)
        inst_ele.find("L1").text=L1Str
        dom.write(dpath)
#------------------------------------------------------------------------------------------------------------
def _psdGetT0OffsetCalc(useT0ModCorr,Ecenter):
    if useT0ModCorr:
        # 2012/03/28 ver.
        #t0_offset_calc = 8.3403 + 91.703*math.exp(-0.081574*Ecenter) + 76.842*math.exp(-0.36659*Ecenter)
        # 2012/04/03 ver.
        t0_offset_calc = 92.233*math.exp(-0.11353*Ecenter) + 63.018*(Ecenter**(-0.45686))
    else:
        t0_offset_calc = 0
    print("t0_moderator_offset",t0_offset_calc)
    return t0_offset_calc
#------------------------------------------------------------------------------------------------------------
def _psdGetL1(UseFastChopper,runNo,energy=False):
    if UseFastChopper:
        dpath = _getDetectorInfoPath(runNo)
        if energy:
            ls = _readParam(dpath,["instrumentInfo","LSample"])
            lc = _readParam(dpath,["instrumentInfo","LChopper"])
            L1 = (float(ls)-float(lc))
        else:
            ls = _readParam(dpath,["instrumentInfo","LChopper"])
            L1 = float(ls)
        #L1 = 34.275
    else:
        L1 = 42000.00 #[20141205 TY m -> mm]
    return L1
#------------------------------------------------------------------------------------------------------------
def _psdGetLaticeSpace(LaticeParam):
    if LaticeParam==1:
        LaticeSpace = 3.1346
    elif LaticeParam==2:#333
        LaticeSpace = 1.0448
    elif LaticeParam==3:#311  add by YK, TK, MM 20181202
        LaticeSpace = 1.6345 #311  add by YK, TK, MM 20181202
    return LaticeSpace
#------------------------------------------------------------------------------------------------------------
def _moniGetL1(UseFastChopper,runNo):
    dpath = _getDetectorInfoPath(runNo)
    lm = _readParam(dpath,["instrumentInfo","LMonitor"])
    if bool(UseFastChopper+1):
        #L1=39.188-7.725
        lc = _readParam(dpath,["instrumentInfo","LChopper"])
        L1 = (float(lm)-float(lc))
        print("L1(FastChopper to Monitor) = ", L1)
    else:
        L1 = float(lm)
        print("L1(Source to Monitor) =", L1)
    return L1
#------------------------------------------------------------------------------------------------------------
def _moniGetL1AtSmp(UseFastChopper,runNo):
    dpath = _getDetectorInfoPath(runNo)
    ls = _readParam(dpath,["instrumentInfo","LSample"])
    if bool(UseFastChopper+1):
        lc = _readParam(dpath,["instrumentInfo","LChopper"])
        L1 = (float(ls)-float(lc))
        print("L1(FastChopper to Monitor at Sample posi) = ", L1)
    else:
        L1 = float(ls)
        print("L1(Source to Monitor at Smaple posi) =", L1)
    return L1
#------------------------------------------------------------------------------------------------------------
def _moniGetL1Van(UseFastChopper,runNo):
    dpath = _getDetectorInfoPath(runNo)
    lv = _readParam(dpath,["instrumentInfo","LVMonitor"])
    if bool(UseFastChopper+1):
        lc = _readParam(dpath,["instrumentInfo","LChopper"])
        L1 = (float(lv) - float(lc))
        print("L1(FastChopper to Vanadium Monitor) = ", L1)
    else:
        L1 = float(lv)
        print("L1(Source to Vanadium Monitor) =", L1)
    return L1
#------------------------------------------------------------------------------------------------------------
def _moniGetT0OffsetCalc(useT0ModCorr,Ecenter):
    if useT0ModCorr:
        # 2012/03/28 ver.
        #t0_offset_calc = 8.3403 + 91.703*math.exp(-0.081574*Ecenter) + 76.842*math.exp(-0.36659*Ecenter)
        # 2012/04/03 ver.
        t0_offset_calc = 92.233*math.exp(-0.11353*Ecenter) + 63.018*(Ecenter**(-0.45686))
    else:
        t0_offset_calc = 0
    print("")
    print("t0_offset_calc =",t0_offset_calc,"microsec")
    print("")
    return t0_offset_calc
#------------------------------------------------------------------------------------------------------------
def _moniGetBoundaryInfo(Emin,Emax,Ecenter,L1):

    #LMonitor   = 39.188
    L1 = 39.188 #TY Add[20141113]
    print("Emax=",Emax)
    print("Ecenter=",Ecenter)
    print("Emin=",Emin)
    print("L1=",L1)

    tof_min    = 2286.2869 * L1 / math.sqrt(Emax)
    tof_center = 2286.2869 * L1 / math.sqrt(Ecenter)
    tof_max    = 2286.2869 * L1 / math.sqrt(Emin)

    boundary = tof_max % 40000
    frameNo = int(( tof_max -(tof_max % 40000) ) / 40000 +1)

    if frameNo !=1:
        Emax2 = Emax
        if frameNo != int((tof_min-(tof_min % 40000)) / 40000 +1): #TY Start
            boundary = boundary
        else:
            boundary = 40000.0
    else:
        Emax2 = Ecenter + math.fabs(Ecenter - Emin)
        #boundary = 2286.2869 * L1 / math.sqrt(Emax2)+(t0_offset+t0_offset_calc)[TY20210119]
        boundary = 2286.2869 * L1 / math.sqrt(Emax2)

    if(Emax2>=40):
        Emax2 = 40
    boundary_max=int(math.ceil(Emax2))

    if(Emin<=0):
        Emin = 0.001
    boundary_min=Emin

    print("tof_min \t= %.4f"%(tof_min))
    print("tof_center \t= %.4f"%(tof_center))
    print("tof_max \t= %.4f"%(tof_max))
    print("boundary \t= %.4f"%(boundary))
    print("frameNo \t= %.4f"%(frameNo))

    return boundary_min,boundary_max,frameNo,boundary
#------------------------------------------------------------------------------------------------------------
def _moniGetBinInfo(boundaryInfo,useEiConv,t0_offset,t0_offset_calc):
    boundary_min,boundary_max,frameNo,boundary = boundaryInfo
    if useEiConv:
        tofBinType=21
        if int(frameNo) !=1:
            params  =[boundary_min,boundary_max,0.002]
            print ("kokoi", t0_offset,type(t0_offset))
            if (t0_offset==-6480.0):
                params  =[boundary_min,boundary_max,0.008]
            #params  =[boundary_min,boundary_max,0.0005] # test 20150902
            t0_offset  =  t0_offset+t0_offset_calc
        else:
            params  =[boundary_min,boundary_max,0.02]
            t0_offset  =  t0_offset+t0_offset_calc

        print("boundary_max \t= %.4f"%(boundary_max))
    else:
        tofBinType=2
        params   = [0.0,120000.0,100]
        t0_offset=t0_offset+t0_offset_calc
    return tofBinType,params,t0_offset

#------------------------------------------------------------------------------------------------------------
def _moniBackgroundSubstraction(ec,ech,background,L1,useEiConv):
    delta_tof = 100
    ecOut = mm.ElementContainer()
    intensity = []
    xbin = ec.PutX()
    ybin = ec.PutY()
    ebin = ec.PutE()
    if useEiConv:
        if background > 0.0:
            for i in range(len(ybin)):
                if xbin[i]<0:
                    if ybin[i]-2286.2869 * L1 *(1.0/ math.sqrt(xbin[i+1]))*background/delta_tof<1.0:
                        intensity.append(1)
                    else:
                        intensity.append(ybin[i]-2286.2869 * L1 *(1.0/ math.sqrt(xbin[i+1]))*background/delta_tof)
                else:
                    if ybin[i]-2286.2869 * L1 *(1.0/ math.sqrt(xbin[i])-1.0/ math.sqrt(xbin[i+1]))*background/delta_tof <1.0:
                        intensity.append(1)
                    else:
                        intensity.append(ybin[i]-2286.2869 * L1 *(1.0/ math.sqrt(xbin[i])-1.0/ math.sqrt(xbin[i+1]))*background/delta_tof)
        else:
            intensity = ybin
            print("background substraction is skipped")
    else:
        for i in range(len(ybin)):
            if ybin[i]-background<1:
                intensity.append(1)
            else:
                intensity.append(ybin[i]-background)

    ecOut.Add("x",xbin)
    ecOut.Add("y",intensity)
    ecOut.Add("e",ebin)
    ecOut.InputHeader(ech)
    ecOut.SetKeys("x","y","e")

    return ecOut

#------------------------------------------------------------------------------------------------------------

def CreateQEMap(dat,startQ,endQ,deltaQ):

    """
    CreateQEMap

    @param dat    (ElementContaienrMatrix)
    @param startQ (double) Q value of range;if -1, auto calculated
    @param endQ   (double) Q value of range;if -1, auto calculated
    @param deltaQ (double) binning of Q
    @retval ECM   (ElementContainerArray)
    """

    QE = md.AdvQECalculation(dat)
    ecm = mm.ElementContainerArray()
    QE.CalcQE(ecm, startQ, endQ, deltaQ)
    del dat

    # Add Header to plot data on M2Plot+ with given KEYs
    hh = ecm.PutHeaderPointer()
    hh.Add("M2PP_X_KEY","Xaxis") # set "Xaxis" as key for X-axis

    return ecm

#------------------------------------------------------------------------------------------------------------

def MonitorAbsorptionCorrection(ec):
    """
    Abosorption Correction of N2 Monitor detector
    @param ec         (ElementContainer)
    @retval  ecout     (ElementContainer)
    """

    #filepath = os.path.join(os.environ["HOME"],"ana","setup","monitor_data.dat")
    filepath = SPD.CheckForInput( "setup", "monitor_data.dat" )
    if filepath=="":
        raise UserWarning( "MonitorAbsorptionCorection >>> not found setup/monitor_data.dat " )
    ne = md.AdvNeutronMonitorDNA(filepath)

    ec2 = ne.GetIntensityAtSample(ec)

    return ec2

#------------------------------------------------------------------------------------------------------------
def OutputQEEC(runNo,dat):
    """
    OutputQE-ECM-ECA

    @param runNo    (int) Run Number
    @param dat    (ElementContaienrMatrix)
    @retval None
    """

    #filenameECAbin = "/home/dnaadmin/ana/tmp/ec/ECA_"+str(runNo)+".bin"
    #filenameECMbin = "/home/dnaadmin/ana/tmp/ec/ECM_"+str(runNo)+".bin"
    #filenameECAnx  = "/home/dnaadmin/ana/tmp/ec/ECA_"+str(runNo)+".nx"
    #filenameECMnx  = "/home/dnaadmin/ana/tmp/ec/ECM_"+str(runNo)+".nx"
    filenameECAbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "tmp", "ec", "ECA_{}.bin".format(str(runNo)))
    filenameECMbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "tmp", "ec", "ECM_{}.bin".format(str(runNo)))
    filenameECAnx  = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "tmp", "ec", "ECA_{}.nx".format(str(runNo)))
    filenameECMnx  = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "tmp", "ec", "ECM_{}.nx".format(str(runNo)))


    flug = os.path.exists(filenameECAbin)
    if flug:
        os.rename(filenameECAbin,filenameECAbin+"_bk1" )
    Mout = mm.WriteSerializationFileBinary(filenameECAbin)
    Mout.Save( dat )
    del( Mout )
    w = mm.NeXusFileIO()
    flug2 = os.path.exists(filenameECAnx)
    if flug2:
        os.rename(filenameECAnx,filenameECAnx+"_bk1" )
    w.Write( dat, filenameECAnx, "AS", 0 )
    del w
    m1 = mm.ElementContainerMatrix()
    m1.Add( dat )
    m1(0)(1).Dump()
    flug3 = os.path.exists(filenameECMbin)
    if flug3:
        os.rename(filenameECMbin,filenameECMbin+"_bk1" )
    Mout2 = mm.WriteSerializationFileBinary(filenameECMbin)
    Mout2.Save( m1 )
    del( Mout2 )
    w2 = mm.NeXusFileIO()
    flug4 = os.path.exists(filenameECMnx)
    if flug4:
        os.rename(filenameECMnx,filenameECMnx+"_bk1" )
    w2.Write( m1,filenameECMnx , "AS", 0 )
    del w2
    del( m1 )

    return
#------------------------------------------------------------------------------------------------------------

def OutputEC(ec,tag):
    """
    @param ec      (ElementContainer)
    @param tag      (string)
    @retval None
    """

    mh = ec.PutHeader()

    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/EC_"+runno+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "EC_{}.bst".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/EC_"+runno+tag+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "EC_{}.bst".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )
    Mout = mm.WriteSerializationFileBinary(filenameECbin)
    Mout.Save( ec )
    del( Mout )

    print("")
    print("output >> ",filenameECbin)

    return

#------------------------------------------------------------------------------------------------------------

def OutputECA(eca,tag):
    """
    @param eca      (ElementContainerArray)
    @param tag      (string)
    @retval None
    """

    mh = eca.PutHeader()
    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.bst".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+tag+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.bst".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )
    Mout = mm.WriteSerializationFileBinary(filenameECbin)
    Mout.Save( eca )
    del( Mout )
    print("")
    print("output >> ",filenameECbin)
    return
#------------------------------------------------------------------------------------------------------------
def OutputECM(ecm,tag):
    """
    @param ecm      (ElementContainerMatrix)
    @param tag      (string)
    @retval None
    """

    mh = ecm.PutHeader()

    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECM_"+runno+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECM_{}.bst".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECM_"+runno+tag+".bst"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECM_{}.bst".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )
    Mout = mm.WriteSerializationFileBinary(filenameECbin)
    Mout.Save( ecm )
    del( Mout )

    print("")
    print("output >> ",filenameECbin)

    return
#------------------------------------------------------------------------------------------------------------
def OutputECAText(eca,tag):
    """
    @param eca      (ElementContainerArray)
    @param tag      (string)
    @retval None
    """

    num_of_ec=eca.PutSize()
    mh = eca.PutHeader()
    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.txt".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+tag+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.txt".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )

    f = open(filenameECbin, "w")

    for i in range(num_of_ec):
        ec = eca.PutPointer(i)
        hh = ec.PutHeaderPointer()
        #hh.Dump()

        Q_vec = hh.PutDoubleVector("XRANGE")
        Q=(Q_vec[0]+Q_vec[1])/2

        EnergyBin_org=ec.PutX()
        EnergyBin_org_size=len(EnergyBin_org)
        EnergyBin =[]
        IntensityBin=ec.PutY()
        ErrorBin=ec.PutE()

        for j in range(EnergyBin_org_size-1):
            EnergyBin_center = (EnergyBin_org[j]+EnergyBin_org[j+1])/2
            if abs(EnergyBin_center)<0.000001:
                   EnergyBin = 0.0
            else:
                   EnergyBin = EnergyBin_center
            f.write(str(Q)+"\t"+str(EnergyBin)+"\t"+str(IntensityBin[j])+"\t"+str(ErrorBin[j])+"\n")
    f.close()

    print("")
    print("output >> ",filenameECbin)

    return
#------------------------------------------------------------------------------------------------------------
def OutputECADAVEText(eca,tag):
    """
    @param eca      (ElementContainerArray)
    @param tag      (string)
    @retval None
    """

    num_of_ec=eca.PutSize()
    mh = eca.PutHeader()
    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+"Dave.grp"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}Dave.grp".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+tag+"Dave.grp"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}Dave.grp".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )

    f = open(filenameECbin, "w")
    Xinfo = "#Number of x-values\r" # Energy Transfer
    Yinfo = "#Number of y-values\r" #Qvalue
    Yinfo += str(int(num_of_ec))+"\r"
    Yvalues = "# yvalues:\r"
    Xvalues = "# xvalues:\r"
    Ivalues = ""
    for i in range(num_of_ec):
        ec = eca.PutPointer(i)
        hh = ec.PutHeaderPointer()
        #hh.Dump()

        if i == 0:
            EnergyBin_org=ec.PutX()
            EnergyBin_org_size=len(EnergyBin_org)
            Xinfo += str(int(EnergyBin_org_size -1))+"\r"
            for j in range(EnergyBin_org_size-1):
                EnergyBin_center = (EnergyBin_org[j]+EnergyBin_org[j+1])/2
                if abs(EnergyBin_center)<0.000001:
                       EnergyBin = 0.0
                else:
                       EnergyBin = EnergyBin_center
                Xvalues += "%.3f\r" %(EnergyBin*1000.0)

        Q_vec = hh.PutDoubleVector("XRANGE")
        Q=(Q_vec[0]+Q_vec[1])/2
        Yvalues += "%.3f\r" %(Q)

        IntensityBin=ec.PutY()
        ErrorBin=ec.PutE()
        if i== 0:
            Ivalues +="#Group: %d" %(i)
        else:
            Ivalues +="\r#Group: %d" %(i)
        for jj in range(len(IntensityBin)):
            if ErrorBin[jj] == -1.0:
                Ivalues+="\r%.4f %.4f" %(0.0, 0.0)
            else:
                Ivalues+="\r%.4f %.4f" %(IntensityBin[jj], ErrorBin[jj])

    f.write(Xinfo)
    f.write(Yinfo)
    f.write(Xvalues)
    f.write(Yvalues)
    f.write(Ivalues)
    f.close()

    print("")
    print("output >> ",filenameECbin)

    return

#------------------------------------------------------------------------------------------------------------
def OutputNeiECAText(eca,tag="_ne"):
    #Output Non equal interval energy transfer ECA text
    #Check RUNNo.
    mh = eca.PutHeader()
    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"
    #Check Filename
    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.txt".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/ECA_"+runno+tag+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "ECA_{}.txt".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )

    #OutPut Main
    SeparatorString = "##############\n"
    Qlist = []
    ETlist = []
    IntErrorText = ""
    for ii in range(eca.PutTableSize()):
        ec = eca.Put(ii)
        Qvec = ec.PutHeaderPointer().PutDoubleVector("XRANGE")
        Qlist.append((Qvec[0]+Qvec[1])*0.5)
        if ii == 0:
            ETlist = ec.PutXList()
        yy = ec.PutYList()
        ee = ec.PutEList()
        for jj in range(len(yy)):
            if float(ee[jj])==-1.0:
                IntErrorText += "%s,%f\n" %("inf",float(ee[jj]))
            else:
                IntErrorText += "%6e,%6e\n" %(float(yy[jj]),float(ee[jj]))

    f = open(filenameECbin, "w")
    for ii in range(len(Qlist)):
        f.write((str)(Qlist[ii])+"\n")
    f.write(SeparatorString)
    for ii in range(len(ETlist)):
        f.write((str)(ETlist[ii])+"\n")
    f.write(SeparatorString)
    f.write(IntErrorText)
    f.close
    print("")
    print("output >> ",filenameECbin)

    return

#------------------------------------------------------------------------------------------------------------

def OutputECText(ec,tag):
    """
    @param ec      (ElementContainer)
    @param tag      (string)
    @retval None
    """

    mh = ec.PutHeader()
    if mh.CheckKey("RUNNUMBER"):
        runno = mh.PutString("RUNNUMBER")
    else:
        runno = "tmp"

    if tag == "_":
        #filenameECbin = "/home/dnaadmin/DNA/tmp/EC_"+runno+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "EC_{}.txt".format(runno))
    else:
        #filenameECbin = "/home/dnaadmin/DNA/tmp/EC_"+runno+tag+".txt"
        filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", "EC_{}.txt".format(runno + tag))

    flug = os.path.exists(filenameECbin)
    if flug:
           os.rename(filenameECbin,filenameECbin+"_bk1" )

    f = open(filenameECbin, "w")

    xbin = ec.PutX()
    ybin = ec.PutY()
    ebin = ec.PutE()


    for i in range(len(ybin)):
        f.write(str((xbin[i]+xbin[i+1])*0.5)+"\t"+str(ybin[i])+"\t"+str(ebin[i])+"\n")
    f.close()

    print("")
    print("output >> ",filenameECbin)

    return

#------------------------------------------------------------------------------------------------------------

def ReadEC(filename):
    """
    @param filename    (string)

    @retval ec      (ElementContainer)
    """

    #filenameECbin = "/home/dnaadmin/DNA/tmp/"+filename
    filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", filename)
    flug = os.path.exists(filenameECbin)
    if flug:
        mread = mm.ReadSerializationFileBinary(filenameECbin)
        ec = mm.ElementContainer()
        mread.Load( ec )
    else:
        print("")
        print("can not find data file")
        print("")
        return

    return ec

#------------------------------------------------------------------------------------------------------------

def ReadECA(filename):
    """
    @param filename  (string)
    @retval eca      (ElementContainer)
    """

    #filenameECbin = "/home/dnaadmin/DNA/tmp/"+filename
    filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", filename)
    flug = os.path.exists(filenameECbin)
    if flug:
        mread = mm.ReadSerializationFileBinary(filenameECbin)
        eca = mm.ElementContainerArray()
        mread.Load( eca )
    else:
        print("")
        print("can not find data file")
        print("")
        return

    return eca

#------------------------------------------------------------------------------------------------------------

def ReadECM(filename):
    """
    @param filename  (string)
    @retval eca      (ElementContainer)
    """

    #filenameECbin = "/home/dnaadmin/DNA/tmp/"+filename #T.Yamada /usr/local/mlf/DNA/tmp -> /home/dnaadamin/DNA/tmp in all functions
    filenameECbin = os.path.join(mu.UtsusemiEnvGetUserDir(), "DNA", "tmp", filename)
    flug = os.path.exists(filenameECbin)
    if flug:
        mread = mm.ReadSerializationFileBinary(filenameECbin)
        ecm = mm.ElementContainerMatrix()
        mread.Load( ecm )
    else:
        print("")
        print("can not find data file")
        print("")
        return

    return ecm

#------------------------------------------------------------------------------------------------------------

def SliceQE(dat,lowerQ,upperQ):
    """
    SliceQE

    @param dat    (ElementContaienrArray)
    @param lowerQ    (double) lowerQ
    @param upperQ    (double) upperQ
    @retval ec    (ElementContainer)
    """

    QE = mm.AdvSliceQE()
    ec = QE.Slice(dat,lowerQ,upperQ)
    hh=ec.PutHeader()
    #NumOfMask = hh.PutInt4("NumOfMask")
    #NumOfEC = hh.PutInt4("NumOfOrigEC")
    #print NumOfMask,NumOfEC
    return ec

#------------------------------------------------------------------------------------------------------------

def SliceQEall(dat,initialQ,finalQ,deltaQ):
    """
    SliceQEall

    @param dat    (ElementContaienrArray)
    @param initialQ  (double)
    @param finalQ    (double)
    @param deltaQ    (double)
    @retval eca    (ElementContainerArray)
    """

    QE = md.AdvSliceQE()
    h=dat.PutHeader()
    eca = mm.ElementContainerArray()
    Xrange = dat(0).PutHeaderPointer().PutDoubleVector("XRANGE")
    if deltaQ < (Xrange[1]-Xrange[0]):
        deltaQ = (Xrange[1]-Xrange[0])
        print("deltaQ is set",str(deltaQ))
    num = int ( float(finalQ-initialQ)/deltaQ )
    for i in range(num):
        lowerQ = initialQ+deltaQ*i
        upperQ = initialQ+deltaQ*(i+1)
        ec = QE.Slice(dat,lowerQ,upperQ)
        hh = ec.PutHeader()
        hh.Add("lowerQ",lowerQ)
        hh.Add("upperQ",upperQ)
        NumOfMask = hh.PutInt4("NumOfMask")
        NumOfEC = hh.PutInt4("NumOfOrigEC")
        Total   = hh.PutDouble("TotalCounts")
        #print NumOfMask,NumOfEC,Total
        ec.InputHeader(hh)
        eca.Add(ec)
    eca.InputHeader(h)
    return eca

#------------------------------------------------------------------------------------------------------------

def OutputPartOfEC(ec,initial,final):
    """
    OutputPartOfEC

    @param ec         (ElementContaienr)
    @param initial    (double)
    @param final      (double)
    @retval EC        (ElementContainer)
    """

    xbin=ec.PutX()
    ybin=ec.PutY()
    ebin=ec.PutE()

    xbin_new =[]
    ybin_new =[]
    ebin_new =[]

    nmin=0
    nmax=0
    if (initial < xbin[0]):
        initial = xbin[0]
    if (final > xbin[len(xbin)-1]):
        final = xbin[len(xbin)-1]

    for i in range(len(xbin)):
        if(initial > xbin[i]):
            nmin += 1
        if(final >= xbin[i]):
            nmax += 1

    for i in range(nmin,nmax):
        xbin_new.append(xbin[i])
        ybin_new.append(ybin[i])
        ebin_new.append(ebin[i])
    xbin_new.append(xbin[nmax])

    EC = mm.ElementContainer()
    EC.Add("x",xbin_new)
    EC.Add("y",ybin_new)
    EC.Add("e",ebin_new)
    EC.SetKeys("x","y","e")

    return EC

#------------------------------------------------------------------------------------------------------------

def GetInformationOfECbin(ec):
    """
    GetInformationOfECbin

    @param EC         (ElementContaienr)
    @retval None
    """

    xbin=ec.PutX()
    print("")
    print("initial bin value is ",xbin[0])
    print("final bin value is ",xbin[len(xbin)-1])
    print("interval of bins is ",xbin[1]-xbin[0])
    print("")

#------------------------------------------------------------------------------------------------------------

def ILambdaCorrDNA(dat,ec,useMonEff):
    """
    I (Lambda) correction for DNA

    @param dat    (ElementContaienrMatrix)
    @param ec     (ElementContainer)
    @param useMonEff  (bool)
    @retval ECM   (ElementContainerMatrix)
    """

    #filepath = os.path.join(os.environ["HOME"],"ana","setup","monitor_data.dat")
    filepath = SPD.CheckForInput( "setup", "monitor_data.dat" )
    if filepath=="":
        raise UserWarning( "ILambdaCorrDNA >>> not found setup/monitor_data.dat " )
    CORR1 = md.AdvILambdaCorrectionDNA()
    #ECM = CORR1.ILCorrection(dat,ec,useMonEff,filepath)
    ECM = mm.ElementContainerMatrix()
    ret = CORR1.ILCorrection(ECM,dat,ec,useMonEff,filepath)
    if not ret:
        raise UserWarning("ILambdaCorrDNA : Error >> check logs on a terminal window")
    del dat
    return ECM


def ILambdaCorrUseMonAtSmpDNA(dat, ec, monDatFile, isHighReso, attenuateVal=0.0):
    """
    I (Lambda) correction by using data of the monitor at sample position for DNA

    @param dat    (ElementContaienrMatrix)
    @param ec     (ElementContainer)
    @param monDatFile (string) information file for composition of monitor
    @param isHighReso (bool) is high resolution or not
    @param attenuateVal (float) 0.0 -> use default value (4.088585)
    @retval ECM   (ElementContainerMatrix)
    """

    filepath = SPD.CheckForInput( "setup", monDatFile )
    if filepath=="":
        raise UserWarning( "ILambdaCorrDNA >>> not found setup/{} ".format(monDatFile) )
    """
    CORR1 = md.AdvILambdaCorrectionDNA()
    #ECM = CORR1.ILCorrection(dat,ec,useMonEff,filepath,True)
    ECM = mm.ElementContainerMatrix()
    ret = CORR1.ILCorrection(ECM,dat,ec,useMonEff,filepath,True)
    """
    CORR1 = md.UtsusemiDNAILambdaCorrectionUseMonAtSample()
    ECM = mm.ElementContainerMatrix()
    CORR1.ILCorrection(ECM, dat, ec, filepath, isHighReso, attenuateVal)
    del dat
    return ECM

#------------------------------------------------------------------------------------------------------------

def GetHistForILC(ec,factor):
    """
    Get EC for I (Lambda) correction(DNA)

    @param ec     (ElementContainer)
    @param factor     (double)
    @retval EC2     (ElementContainer)
    """

    CORR1 = md.AdvNeutronMonitorDNA()
    EC2 = CORR1.GetIntensityAtSample(ec)
    EC3=EC2.Mul(factor)
    return EC3

#------------------------------------------------------------------------------------------------------------

def SolidAngleCorrDNA(dat,useDetEff,useAbsoCorr,useEffCorr,sampletype,sampleDataFile,DetEffDataPath):
    """
    Solid Angle correction for DNA

    @param dat    (ElementContaienrMatrix)
    @param useDetEff   (bool)
    @param useAbsoCorr (bool)
    @param useEffCorr  (bool)
    @param sampletype  (string) sample/cell
    @param sampleDataPath  (string)
    @retval ECM   (ElementContainerMatrix)
    """

    #sampleDataPath  = os.path.join(os.environ["HOME"],"ana","setup","test_sample_data.dat")

    if os.path.exists(sampleDataFile):
        sampleDataPath = sampleDataFile
    else:
        #sampleDataPath   = os.path.join(os.environ["HOME"],"ana","setup",sampleDataFile)
        sampleDataPath = SPD.CheckForInput( "setup", sampleDataFile )
        if sampleDataPath=="":
            raise UserWarning( "SolidAngleCorrDNA >>> not found setup/"+sampleDataFile )

    #detectorDataPath = os.path.join(os.environ["HOME"],"ana","setup","detector_data.dat")
    detectorDataPath = SPD.CheckForInput( "setup", "detector_data.dat" )
    if detectorDataPath=="":
        raise UserWarning( "SolidAngleCorrDNA >>> not found setup/detector_data.dat" )
    #corrEffDataPath  = os.path.join(os.environ["HOME"],"ana","setup","corr_eff_data.dat")
    corrEffDataPath = SPD.CheckForInput( "setup", "corr_eff_data.dat" )
    if corrEffDataPath=="":
        raise UserWarning( "SolidAngleCorrDNA >>> not found setup/corr_eff_data.dat" )

    #TY Modified [20141210]
    if os.path.exists(DetEffDataPath):
        corrEffDataPath = DetEffDataPath
    else:
        print("SolidAngleCorrectionDNA ---> Detector efficiency file is not exist.")
        #corrEffDataPath  = os.path.join(os.environ["HOME"],"ana","setup","corr_eff_data.dat")
        #corrEffDataPath  = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","setup","corr_eff_data.dat")
        corrEffDataPath = SPD.CheckForInput("setup", "corr_eff_data.dat")
        print("SolidAngleCorrectionDNA ---> %s is set as detector efficiency file insted of %s" %(corrEffDataPath, DetEffDataPath))
    #TY End [20141210]
    CORR1 = md.AdvSolidAngleCorrectionDNA()
    #ECM = CORR1.SACorrection(dat,useDetEff,useAbsoCorr,sampleDataPath,detectorDataPath)
    #sampletype = sampletype.lower()
    #if (sampletype == "cell" or sampletype == "sample"):
    if (sampletype == "cell" or sampletype == "sample" or sampletype == "other"):
        #ECM = CORR1.SACorrection(dat,useDetEff,useAbsoCorr,useEffCorr,sampletype,sampleDataPath,detectorDataPath,corrEffDataPath)
        ECM = mm.ElementContainerMatrix()
        ret = CORR1.SACorrection(ECM,dat,useDetEff,useAbsoCorr,useEffCorr,sampletype,sampleDataPath,detectorDataPath,corrEffDataPath)
        del dat
    else:
        print("please select \"sample\" or \"cell\" ")
        ECM = dat
        del dat
    return ECM

#------------------------------------------------------------------------------------------------------------
def DoQEMask(ECA,filename="QEMask.txt"):
    """
    Mask QE grape , AS
    @param eca (ElementContainerArray)
    @param filename (string)
    @retval None
    """
    #filepath = os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","ElasticScan",filename)
    filepath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana",mu.UtsusemiEnvGetInstCode(),"ElasticScan",filename)
    f=open(filepath)
    #ECA = ReadECA("ECA_654_QE.bst")
    lines = f.readlines()
    f.close()


    lower=[]
    upper=[]

    for line in lines:
        comment = re.search("#", line)
        if not (comment):
            if re.search("\n", line):
                line = line.split("\n")[0]
            flug1 = re.search(",", line)
            if flug1:
                if float(line.split(",")[0]) > float(line.split(",")[1]):
                    lower.append(line.split(",")[1])
                    upper.append(line.split(",")[0])
                elif float(line.split(",")[1]) >= float(line.split(",")[0]):
                    lower.append(line.split(",")[0])
                    upper.append(line.split(",")[1])

    numOfQ = ECA.PutSize()
    Qmask = []
    x = []

    for j in range(numOfQ):
        hh = ECA(j).PutHeader()
        Xrange = hh.PutDoubleVector("XRANGE")
        XrangeCenter = (Xrange[0]+Xrange[1])*0.5
        mask = 0
        for i in range(len(lower)):
            if (XrangeCenter >= float(lower[i])) and (XrangeCenter < float(upper[i])):
                mask = 1
        hh.OverWrite("MASKED",mask)
        ECA(j).InputHeader(hh)

    #for j in range(numOfQ):
    #    hh = ECA(j).PutHeader()
    #    Xrange = hh.PutDouble("MASKED")
    #    print Xrange

#------------------------------------------------------------------------------------------------------------
def PeakFitSimple0(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,xbin_start,xbin_end,useDomain,flug):
    """
    PeakFitting script by using Levmar, gauss, AS Fit
    @param ec (ElementContainer)
    @param func               (string)
    @param fit_boundary_ratio (float)
    @param peak_hight         (float)
    @param peak_position      (float)
    @param peak_fwhm          (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    @param flug                (bool)
    """

    return PF.PeakFitSimple0(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,xbin_start,xbin_end,useDomain,flug)

#------------------------------------------------------------------------------------------------------------

def PeakFitSimple(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,peak_back,xbin_start,xbin_end,useDomain,flug,flug3):
    """
    PeakFitting script by using Levmar,gauss+constant AS Fit
    @param ec (ElementContainer)
    @param func               (string)
    @param fit_boundary_ratio (float)
    @param peak_hight         (float)
    @param peak_position      (float)
    @param peak_fwhm          (float)
    @param peak_back          (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    @param flug                (bool)
    @param flug3                (bool)
    """

    return PF.PeakFitSimple(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,peak_back,xbin_start,xbin_end,useDomain,flug,flug3)

#------------------------------------------------------------------------------------------------------------

def PeakFit(ec,function,param,param_ub,param_lb,fit_region,useDomain,NumOfItteration,plotflug):
    """
    PeakFitting script by using Levmar, AS Fit
    @param ec    (ElementContainer)
    @param function        (string)
    @param param           (string)
    @param param_lb        (string)
    @param param_ub        (string)
    @param useDomain       (bool)
    @param NumOfItteration (int)
    @param plotflug        (bool)
    """

    return PF.PeakFit(ec,function,param,param_ub,param_lb,fit_region,useDomain,NumOfItteration,plotflug)

#------------------------------------------------------------------------------------------------------------

def PeakFitNotUseWeight(ec,function,param,param_ub,param_lb,fit_region,useDomain,NumOfItteration,plotflug):
    """
    PeakFitting script by using Levmar, AS Fit
    @param ec    (ElementContainer)
    @param function        (string)
    @param param           (string)
    @param param_lb        (string)
    @param param_ub        (string)
    @param useDomain       (bool)
    @param NumOfItteration (int)
    @param plotflug        (bool)
    """

    return PF.PeakFitNotUseWeight(ec,function,param,param_ub,param_lb,fit_region,useDomain,NumOfItteration,plotflug)

#------------------------------------------------------------------------------------------------------------

def PeakFitTriangle(ec,fit_boundary_ratio,hight,boundary,background,xbin_start,xbin_end,useDomain):
    """
    PeakFitting script by using Levmar,Triangle AS Fit
    @param ec (ElementContainer)
    @param fit_boundary_ratio (float)
    @param hight              (float)
    @param boundary           (string)
    @param background         (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    """

    return PF.PeakFitTriTrape(ec,"tri c",fit_boundary_ratio,hight,boundary,background,xbin_start,xbin_end,useDomain,True,True)

#------------------------------------------------------------------------------------------------------------

def PeakFitTrapezoid(ec,fit_boundary_ratio,hight,boundary,background,xbin_start,xbin_end,useDomain):
    """
    PeakFitting script by using Levmar,Triangle AS Fit
    @param ec (ElementContainer)
    @param fit_boundary_ratio (float)
    @param hight              (float)
    @param boundary           (string)
    @param background         (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    """

    return PF.PeakFitTriTrape(ec,"trp c",fit_boundary_ratio,hight,boundary,background,xbin_start,xbin_end,useDomain,True,True)

#------------------------------------------------------------------------------------------------------------

def PeakFitSimpleECA(eca,fit_boundary_ratio,xbin_start,xbin_end,useDomain):
    """
    PeakFitting script by using Levmar, AS Fit
    @param eca (ElementContainerArray)
    @param fit_boundary_ratio (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    """
    p = mp.MPlot()
    p2 = mp.MPlot()

    p.SetTraceNum(2)
    p2.SetTraceNum(1)

    num_of_ec=eca.PutSize()

    Area = []
    Area_e = []
    Fwhm = []
    Fwhm_e = []
    Intensity = []
    Intensity_e = []
    Q_Axis = []

    for i in range(num_of_ec):
       ec = eca.PutPointer(i)
       ret0,ret1,ret2 = GetECPeakInfo(ec," ",xbin_start,xbin_end,2)
       print("fitting ",i)

       ec2,result_phys = PF.PeakFitSimple(ec,"g c",fit_boundary_ratio,ret0,-0.02,ret1,ret2,xbin_start,xbin_end,useDomain,True,False)
       p.SetXScale(xbin_start-abs(xbin_start*0.2),xbin_end+abs(xbin_end*0.2))
       p.AddData(ec)
       p.AddData(ec2)
       p.SetPlotParam(i*2+1,mc="b",lc="b")
       p.SetPlotParam(i*2+2,ls="-",lw=8,mk="",eb=False,lc="r")

       p.ChangePage(i+2)

       lower_Q = ec.PutHeader().PutDouble("lowerQ")
       upper_Q = ec.PutHeader().PutDouble("upperQ")
       Q_Axis.append(lower_Q)
       if i==num_of_ec-1:
               Q_Axis.append(upper_Q)
       Area.append(result_phys[0])
       Area_e.append(result_phys[1])
       Fwhm.append(result_phys[2])
       Fwhm_e.append(result_phys[3])
       Intensity.append(result_phys[4])
       Intensity_e.append(result_phys[5])

    eArea = mm.ElementContainer()
    eArea.Add("x",Q_Axis)
    eArea.Add("y",Area)
    eArea.Add("e",Area_e)
    eArea.SetKeys("x","y","e")
    eFwhm = mm.ElementContainer()
    eFwhm.Add("x",Q_Axis)
    eFwhm.Add("y",Fwhm)
    eFwhm.Add("e",Fwhm_e)
    eFwhm.SetKeys("x","y","e")
    ePeak = mm.ElementContainer()
    ePeak.Add("x",Q_Axis)
    ePeak.Add("y",Intensity)
    ePeak.Add("e",Intensity_e)
    ePeak.SetKeys("x","y","e")
    p2.ChangePage(1)
    p2.AddData(eArea)
    p2.ChangePage(2)
    p2.AddData(eFwhm)
    p2.ChangePage(3)
    p2.AddData(ePeak)

#------------------------------------------------------------------------------------------------------------
def SearchExIDFromRunNo(runNo):
    """
    SearchExIDFromRunNo(runNo)
    @param runNo (int)
    @retval bc
    """
    #search_dir=os.path.join(os.environ["MLF_USR_DIR"],"ana","xml")
    search_dir=os.path.join("/","usr","local","mlf","DNA","ana","xml") #20141220[Yamada]
    search_pattern="<runNo>"+str(runNo)+"</runNo>"
    file_name_list = os.listdir(search_dir)
    ExIDFlug = False

    for dir_name in file_name_list:
      if dir_name[0:2] == "ex":
         search_dir2=os.path.join(search_dir,dir_name)
         file_name_list2 = os.listdir(search_dir2)
         for file_name in file_name_list2:
              if file_name=="params.xml":
                 f=open(os.path.join(search_dir2,"params.xml"))
                 lines = f.readlines()
                 f.close()
                 for line in lines:
                     m = re.search(search_pattern, line)
                     if m:
                         ExID = dir_name
                         ExIDFlug = True

    result = []
    # load a start-time and end-time information from params.xml
    if ExIDFlug:
        filepath = os.path.join(search_dir,ExID,"params.xml")
    else:
        print("")
        print("params.xml file is not found")
        filepath = os.path.join(search_dir,"paramsTime.xml")
        print("use "+filepath+" instead of regular params.xml")
        print("you can input start-time and end-time and runnumber in paramsTime.xml, please execute InputTimeInfoManual()")
        ExID = "unknown"

    xml = ElementTree(file=filepath)
    xmlRoot = xml.getroot()
    measRsltLst=xmlRoot.find('exInfo').find('measRsltLst').findall('measRslt')

    for measRslt in measRsltLst:
        if int(measRslt.find('runNo').text) == runNo:
            startDate = str(measRslt.find('startDate').text)
            endDate = str(measRslt.find('endDate').text)
            startflug = re.search(" ", startDate)
            endflug = re.search(" ", endDate)
    if startDate != "None":
        if startflug:
            result.append(startDate.split(" ")[0])
            result.append(startDate.split(" ")[1])
        else:
            result.append("NAN")
            result.append("NAN")
        if endflug:
            result.append(endDate.split(" ")[0])
            result.append(endDate.split(" ")[1])
        else:
            #endDateFsec = os.path.getctime(os.path.join(search_dir,ExID,"params.xml"))
            yy,mm,dd= (startDate.split(" ")[0]).split("-")
            #endDateFsec = os.path.getctime(os.path.join(os.environ["MLF_DATA_DIR"],"DNA"+str(runNo).zfill(6)+"_"+yy+mm+dd,"DNA"+str(runNo).zfill(6)+"_02_254_000.edb"))
#            dataPath = os.path.join(os.environ["MLF_DATA_DIR"],"DNA"+str(runNo).zfill(6)+"_"+yy+mm+dd) T.Yamada comment out [121217]
            dataPath = os.path.join(os.environ["MLF_DATA_DIR"],"DNA"+str(runNo).zfill(6)+"_"+yy+mm+dd,"DNA"+str(runNo).zfill(6)+"_00_004_000.edb") #T.Yamada Add [121217]
            if not (os.path.exists(dataPath)):
                return "NAN","NAN","NAN","NAN"
            else:
                endDateFsec = os.path.getctime(dataPath)
                endDateF=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(endDateFsec))
                result.append(endDateF.split(" ")[0])
                result.append(endDateF.split(" ")[1])
    else:
        return "NAN","NAN","NAN","NAN"

    print("")
    print("SearchExID >> runNo =",runNo)
    print("SearchExID >> ExID =",ExID)
    #print "run_start_time =",result[0],result[1][0:8]
    #print "run_end_time   =",result[2],result[3][0:8]
    print("SearchExID >> run_start_time =",result[0],result[1][0:8])
    print("SearchExID >> run_end_time   =",result[2],result[3][0:8])

    return result[0],result[1][0:8],result[2],result[3][0:8]
#------------------------------------------------------------------------------------------------------------
def GetRunInfo(runNo):
    """
    SearchExIDFromRunNo(runNo)
    @param runNo (int)
    @retval bc
    """
    time1,time2,time3,time4 = SearchExIDFromRunNo(runNo)
    flug1 = re.search("NAN", time1)
    flug2 = re.search("NAN", time2)
    flug3 = re.search("NAN", time3)
    flug4 = re.search("NAN", time4)
    if (not flug1) and (not flug2) and (not flug3) and (not flug4):
       bc = getBeamCurrent(time1.replace("-","/"),time2,time3.replace("-","/"),time4)
    if (flug1) or (flug2) or (flug3) or (flug4):
       print("Failed to get run-time-information.")
       bc =1
    return bc
#------------------------------------------------------------------------------------------------------------
def GetRunInfoTime(runNo,TimeParam):
    """
    SearchExIDFromRunNo(runNo)
    @param runNo (int)
    @param TimeParam (string)
    @retval bc
    """
    time1,time2,time3,time4 = SearchExIDFromRunNo(runNo)
    flug1 = re.search("NAN", time1)
    flug2 = re.search("NAN", time2)
    flug3 = re.search("NAN", time3)
    flug4 = re.search("NAN", time4)
    if (not flug1) and (not flug2) and (not flug3) and (not flug4):
        starttime = time1+" "+time2
        endtime = time3+" "+time4
        TimeList = TimeParam.split(",")
        st0 = datetime.datetime(*time.strptime(starttime,"%Y-%m-%d %H:%M:%S")[0:6])
        et0 = datetime.datetime(*time.strptime(endtime,"%Y-%m-%d %H:%M:%S")[0:6])

        if(float(TimeList[0])>0):
            dts0 = datetime.timedelta(0,float(TimeList[0]))
            st2 = st0 + dts0
        else:
            st2 = st0

        if(float(TimeList[1])>0):
            dte0 = datetime.timedelta(0,float(TimeList[1]))
            et2 = st0 + dte0
        else:
            et2 = et0

        if et2>et0:
          print("The input-end-parameters are exceed the measurement-time.")
          et2 = et0

        starttimeOut = (str(st2)).split(" ")
        endtimeOut = (str(et2)).split(" ")

        bc = getBeamCurrent(starttimeOut[0].replace("-","/"),starttimeOut[1],endtimeOut[0].replace("-","/"),endtimeOut[1])

        if (bc <0):
            bc = 1

    if (flug1) or (flug2) or (flug3) or (flug4):
       print("Failed to get run-time-information.")
       bc =1

    return bc
#------------------------------------------------------------------------------------------------------------
def NormByBeamWithParams(dat,runNo):
    """
    @param dat        (ElementContainer,-Array,-Matrix)
    @param runNo (int)
    """

    bc = GetRunInfo(runNo)
    if bc<0:
        print("BeamCurrent is not invalid.")
        return dat
    dat.MulMySelf(1/float(bc))

#------------------------------------------------------------------------------------------------------------
def CheckRealTime(runNo,TimeParam):

    time1,time2,time3,time4 = SearchExIDFromRunNo(runNo)

    flug1 = re.search("NAN", time1)
    flug2 = re.search("NAN", time2)
    flug3 = re.search("NAN", time3)
    flug4 = re.search("NAN", time4)

    if (not flug1) and (not flug2) and (not flug3) and (not flug4):
        starttime = time1+" "+time2
        endtime = time3+" "+time4
        TimeList = TimeParam.split(",")
        st0 = datetime.datetime(*time.strptime(starttime,"%Y-%m-%d %H:%M:%S")[0:6])
        et0 = datetime.datetime(*time.strptime(endtime,"%Y-%m-%d %H:%M:%S")[0:6])

        if(float(TimeList[0])>0):
            dts0 = datetime.timedelta(0,float(TimeList[0]))
            st2 = st0 + dts0
        else:
            st2 = st0

        if(float(TimeList[1])>0):
            dte0 = datetime.timedelta(0,float(TimeList[1]))
            et2 = st0 + dte0
        else:
            et2 = et0

        if et2>et0:
            print("The input-end-parameters are exceed the measurement-time.")
            et2 = et0

        starttimeOut = (str(st2)).split(" ")
        endtimeOut = (str(et2)).split(" ")

        print("")
        print("TemperatureRead >> Start :",starttimeOut[0],starttimeOut[1])
        print("TemperatureRead >> End   :",endtimeOut[0],endtimeOut[1])

        return starttimeOut[0],starttimeOut[1],endtimeOut[0],endtimeOut[1]

    if (flug1) or (flug2) or (flug3) or (flug4):

        print("Failed to get run-time-information.")

        return "NAN","NAN","NAN","NAN"
#------------------------------------------------------------------------------------------------------------
def DownloadLogFile(startday,endday):

    filename = 'Log_TC_'
    filename1 = filename + startday + ".csv"
    filename2 = filename + endday + ".csv"
    url1 = "http://10.107.2.62/log/"+filename1
    #savepath1 = os.path.join(os.environ["HOME"],"ana","tmp",filename1) #20141220[Yamada]
    savepath1 = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp",filename1) #20141220[Yamada]
    #savepath1 = "/usr/local/mlf/log/mw/"+filename1
    url2 = "http://10.107.2.62/log/"+filename2
    #savepath2 = os.path.join(os.environ["HOME"],"ana","tmp",filename2) #20141220[Yamada]
    savepath2 = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp",filename2) #20141220[Yamada]
    #savepath2 = "/usr/local/mlf/log/mw/"+filename2

    if(os.path.exists(savepath1)):
        if CheckLogFile(url1,savepath1):
            urllib.urlretrieve(url1,savepath1)
    else:
        if CheckLogCsvFileAtWeb(url1):
            urllib.urlretrieve(url1,savepath1)

    if(startday != endday):
        if(os.path.exists(savepath2)):
            if CheckLogFile(url2,savepath2):
                urllib.urlretrieve(url2,savepath2)
        else:
            if CheckLogCsvFileAtWeb(url2):
                urllib.urlretrieve(url2,savepath2)

    return
#------------------------------------------------------------------------------------------------------------
def DownloadLogFileZip(startday,endday):

    filename = 'Log_TC_'
    filename1 = filename + startday + ".csv"
    filename2 = filename + endday + ".csv"
    filenameZip1 = filename + startday + ".zip"
    filenameZip2 = filename + endday + ".zip"

    url1 = "http://10.107.2.62/log/"+filename1
    savepath1 = "/usr/local/mlf/log/mw/"+filename1
    url2 = "http://10.107.2.62/log/"+filename2
    savepath2 = "/usr/local/mlf/log/mw/"+filename2

    urlZip1 = "http://10.107.2.62/log/"+filenameZip1
    savepathZip1 = "/usr/local/mlf/log/mw/"+filenameZip1
    urlZip2 = "http://10.107.2.62/log/"+filenameZip2
    savepathZip2 = "/usr/local/mlf/log/mw/"+filenameZip2

    if(os.path.exists(savepathZip1)):
        if CheckLogFile(urlZip1,savepathZip1):
            urllib.urlretrieve(urlZip1,savepathZip1)
    else:
        if CheckLogZipFileAtWeb(urlZip1):
            urllib.urlretrieve(urlZip1,savepathZip1)
        else:
            if(os.path.exists(savepath1)):
                if CheckLogFile(url1,savepath1):
                    urllib.urlretrieve(url1,savepath1)
            else:
                if CheckUrlConnection(url,80):
                    urllib.urlretrieve(url1,savepath1)

    if(startday != endday):
        if(os.path.exists(savepathZip2)):
            if CheckLogFile(urlZip2,savepathZip2):
                urllib.urlretrieve(urlZip2,savepathZip2)
        else:
            if CheckLogZipFileAtWeb(urlZip2):
                urllib.urlretrieve(urlZip2,savepathZip2)
            else:
                if(os.path.exists(savepath2)):
                    if CheckLogFile(url2,savepath2):
                        urllib.urlretrieve(url2,savepath2)
                else:
                    if CheckUrlConnection(url,80):
                        urllib.urlretrieve(url2,savepath2)
    return
#------------------------------------------------------------------------------------------------------------
def CheckLogFile(url,savepath):

    saveTimeSec = os.path.getmtime(savepath)
    saveTimeString = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(saveTimeSec))
    saveTime = datetime.datetime(*time.strptime(saveTimeString,"%Y-%m-%d %H:%M:%S")[0:6])

    if CheckUrlConnection(url,80):
        r=urllib.urlopen(url)
        head = r.info()
        modifiedGMT = head.getdate("last-modified")
        if modifiedGMT==None:
            log_file_exist = False
            print("checkTempLog >> log file is not exist")
            return False
        else:
            log_file_exist = True
            modifiedGMTString = time.strftime("%Y-%m-%d %H:%M:%S",modifiedGMT)
            now = datetime.datetime.today()
            modifiedGMTTime = datetime.datetime(*time.strptime(modifiedGMTString,"%Y-%m-%d %H:%M:%S")[0:6])
            dTime = datetime.timedelta(0,9*3600)
            modifiedJPNTime = dTime + modifiedGMTTime

            #print "current-time       \t= ",now
            print("checkTempLog >> last-modified time \t= ",modifiedJPNTime)
            print("checkTempLog >> save-time          \t= ",saveTime)

            if saveTime > modifiedJPNTime:
                print("checkTempLog >> save file is latest")
                return False
            elif saveTime <= modifiedJPNTime:
                print("checkTempLog >> save file is old")
                return True
    else:
        return False
#------------------------------------------------------------------------------------------------------------
def CheckLogZipFileAtWeb(url):
    if CheckUrlConnection(url,80):
        r=urllib.urlopen(url)
        head = r.info()
        modifiedGMT = head.getdate("last-modified")
        if modifiedGMT==None:
            log_file_exist = False
            print("checkTempLog >>",url,"is not exist")
            return False
        else:
            return True
    else:
        return False
#------------------------------------------------------------------------------------------------------------
def CheckLogCsvFileAtWeb(url):

    if CheckUrlConnection(url,80):
        r=urllib.urlopen(url)
        head = r.info()
        modifiedGMT = head.getdate("last-modified")
        if modifiedGMT==None:
            log_file_exist = False
            print("checkTempLog >>",url,"is not exist")
            return False
        else:
            return True
    else:
        return False
#------------------------------------------------------------------------------------------------------------
def CheckUrlConnection(url,port):

    host = url.split("/")[2]
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
      sock.connect((host,port))
    except:
      print(url,": connection error")
      return False

    return True
#------------------------------------------------------------------------------------------------------------
def DoMask(dat,filename="mask.txt"):
    """
    MASKED flag controled by file.
    @param dat (ElementContainerMatrix)
    @param filename (string) filename of mask information
    """

    PROCESS = "DoMask"

    print("DoMask in DNA >>> executing...")
    #from ana.Reduction.DataReduct_SJY import ChopperMask

    if os.path.exists(filename):
        FilePath=filename
    else:
        #FilePath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",filename)
        FilePath=os.path.join(mu.UtsusemiEnvGetBaseDir(),mu.UtsusemiEnvGetInstCode(),"ana","xml",filename)
        if os.path.exists(FilePath):
            #ChopperMask(dat,None,FilePath)
            BaseCom.DoMask(dat,filename)
        else:
            #if "UTSUSEMI_USR_PRIV_HOME" in os.environ:
            #    FilePath=os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",filename)
            udir = mu.UtsusemiEnvGetUserDir()
            if udir!="":
                FilePath=os.path.join(udir,"ana",mu.UtsusemiEnvGetInstCode(),"Mask",filename)
            else:
                #FilePath=os.path.join(os.environ["HOME"],"ana","xml",filename)
                FilePath=os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",filename)
            if os.path.exists(FilePath):
                #ChopperMask(dat,None,FilePath)
                BaseCom.DoMask(dat,FilePath)
            else:
                raise UserWarning("DoMask >>> ERROR:"+filename+" is not found.")

    print( "DoMask in DNA found file path = "+FilePath )
    ## Add Header Info
    SS = PROCESS+"(dat, filename=%s)" % (FilePath)
    hh = dat.PutHeaderPointer()
    process_vect = hh.PutStringVector("DATAPROCESSED")
    process_vect.append(SS)
    if hh.CheckKey("DATAPROCESSED")==0:
        hh.Add("DATAPROCESSED",process_vect)
    else:
        hh.OverWrite("DATAPROCESSED",process_vect)

#------------------------------------------------------------------------------------------------------------
def MutiplyConstant(dat, factor):
    """
    Multiplication
    @param dat        (ElementContainer,-Array,-Matrix)
    @param factor     (double) factor
    @retval ECM   (ElementContainerArray)
    """

    dat.MulMySelf(float(factor))
#------------------------------------------------------------------------------------------------------------
def getBeamCurrent(start_day="2009/5/30", start_time="10:00:00", end_day="2009/5/30", end_time="11:00:00" ):
    """
    get Beam current from web and calculate summation of the number of shots and protons
    @param start_day  (string) the day of measurement start [yyyy/mm/dd]
    @param start_time (string) the time of measurement start [hh:mm:ss]
    @param end_day    (string) the day of measurement end [yyyy/mm/dd]
    @param end_time   (string) the time of measurement end [hh:mm:ss]
    @retval beamCurrent        the number of protons [TelaProtons]
    """
    BaseCom.getBeamCurrent(start_day , start_time , end_day , end_time, isCT8n=True ) ##[inamura 180507]add isCT8n
#------------------------------------------------------------------------------------------------------------
def DNAGetRockingCurve(StartEndRunNo,StartEndpsd,StartEndPix,LambdaParam,mode,startomega,domega,OmgPlot):
    """
    Get rocking curver
    TYGetRockingCurve(StartEndRunNo=" ",StartEndpsd=" ",StartEndPix=" ",
                        LambdaParam="",mode=111,startOmega=0.0,domega=0.5,OmgPlot=True):
    @param StartEndRunNo (string) start and end runNo
    @param StartEndpsd (string) start and end psd
    @param StartEndPix (string) start and end pixel
    @param LambdaParam (string) lambda center and delta lambda
    @param mode (ing) select Si analyzer 111 or 333
    @param startOmega (double) start omega [deg]
    @param domega (double) delta omega [deg]
    @param output (bool) output as omega (True) or runNo (False)
    @retval EC      (ElementContainer)
    """
    import utsusemi.DNA.ana.Reduction.RockingCurve as RC
    return RC.TYDNAGetRockingCurve(StartEndRunNo,StartEndpsd,StartEndPix,LambdaParam,mode,startomega,domega,OmgPlot)
#------------------------------------------------------------------------------------------------------------
def T0bfileCheck(RunNo, DetType):
    """
    Check created time between t0b files and edb files
    @param RunNo(int) RunNo
    @param DetType(string) Detector Type: uPSD, N2Mon, PSD
    """

    printheader = "t0b file Checker -->>"
    #t0data_dir = os.path.join(os.environ["HOME"],"ana","tmp")
    #data_dir = os.path.join(os.environ["UTSUSEMI_DATA_DIR"],os.environ["UTSUSEMI_SYS_NAME"])
    t0data_dir = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp")
    data_dir = mu.UtsusemiEnvGetInstDataDir()
    footer = "*.t0b"
    if DetType == "uPSD":
        footer = "0[01]*.t0b"
    elif DetType == "PSD":
        footer = "03_0*.t0b"
    elif DetType == "N2MON":
        footer = "02*.t0b"
    elif DetType == "TRIGNET":
        footer = "03_128*.t0b"

    instCode = mu.UtsusemiEnvGetInstCode()
    #t0files = "%s%06d_%s" %(os.environ["UTSUSEMI_SYS_NAME"],RunNo,footer)
    t0files = "%s%06d_%s" %(instCode,RunNo,footer)
    t0list = glob.glob(os.path.join(t0data_dir,t0files))
    if len(t0list)>0:
        t0list.sort()
        t0file = t0list[-1]

        if os.path.exists(t0file):
            edbfile = os.path.basename(t0file).replace("t0b","edb")
            #edb_dir = "%s%06d*" %(os.environ["UTSUSEMI_SYS_NAME"],RunNo)
            edb_dir = "%s%06d*" %(instCode,RunNo)
            edbfile = glob.glob(os.path.join(data_dir,edb_dir,edbfile))[-1]
            if os.path.getmtime(t0file) < os.path.getmtime(edbfile):
                print(printheader, "t0b files are older than the edb files.")
                for tempfile in t0list:
                    print(printheader, "Delete>>"+tempfile)
                    os.remove(tempfile)
            else:
                print(printheader, "t0b files were already generated.", os.path.getmtime(t0file), os.path.getmtime(edbfile))
            #print edbfile
        else:
            print(printheader, "t0b files does not exists.")
            for tempfile in glob.glob(os.path.join(t0data_dir,'*.t0b')):
                print(printheader, "Delete >> "+tempfile)
                os.remove(tempfile)
    else:
        print(printheader, "t0b files does not exists.")
#------------------------------------------------------------------------------------------------------------
def CheckSampleTempByRunNumber(runNo,temptype):
        """
         Check Sample Temperature by using LakeShore-340
         @param runNo      (int)
         @param temptype   (string)
         @retval EC        (ElementContainer)

        """
        TimeParam="-1.0,-1.0"
        startday,starttime,endday,endtime = CheckRealTime(runNo,TimeParam)
        DownloadLogFile(startday,endday)
        import utsusemi.DNA.ana.Reduction.TempMonitor as TM
        resultEC = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype,True)
        resultEC.AddToHeader("RUNNUMBER",str(runNo))
        return resultEC
#------------------------------------------------------------------------------------------------------------
def DoMaskForEachEC(ECM):
    md.UtsusemiSetMaskDNA(ECM)
#------------------------------------------------------------------------------------------------------------
def MergeWithWeight(DAT1,DAT2):
    flag1 = isinstance(DAT1,mm.ElementContainer) or \
            isinstance(DAT1,mm.ElementContainerArray) or \
            isinstance(DAT1,mm.ElementContainerMatrix)

    flag2 = isinstance(DAT2,mm.ElementContainer) or \
            isinstance(DAT2,mm.ElementContainerArray) or \
            isinstance(DAT2,mm.ElementContainerMatrix)

    if flag1 and flag2:
        return DAT1.MergeWithWeight(DAT2)
    else:
        return None
#------------------------------------------------------------------------------------------------------------
def MergeWithWeightList(DATS):
    if isinstance(DATS,list):
        if len(DATS)>=1:
            DAT=None
            for dat in DATS:
                flag = isinstance(dat,mm.ElementContainer) or \
                       isinstance(dat,mm.ElementContainerArray) or \
                       isinstance(dat,mm.ElementContainerMatrix)

                if flag:
                    if DAT==None:
                        DAT=dat
                    else:
                        DAT=DAT.MergeWithWeight(dat)
            return DAT
    return None
#------------------------------------------------------------------------------------------------------------

