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

#####################
## Command Sequence of Elastic Scan
#####################

# special reserved word for commands history
from __future__ import print_function
HISTORY = None
# reserved words for return value in this.
DAT = None
ECA = None
EC = None

import Manyo as mm
import Manyo.Utsusemi as mu
import utsusemi.ana.Reduction.BaseCommandsInEla as BaseCom
import utsusemi.DNA.ana.Reduction.PeakFitBase as PF
import utsusemi.DNA.ana.Reduction.BaseCommandsDNA as BaseComDNA
import utsusemi.DNA.ana.Reduction.TempMonitor as TM
import utsusemi.DNA.ana.Reduction.PeakIntegral as PI
import os
import re
import glob
import math
import datetime
import uGao.MPlot as mp
import Cmm

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

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

def GetDataOfDNA(runNo=314,HwParam=" ",LambParam=" ",QParam=" ",TimeParam=" ",initFile="GetQEDataOfDNA.ini",outputData="QE",fileTag="_" ,search_dir=""):
    """
    Load EventData and convert to QE map
    - GetHistogramHW(runNo,dHW,hw_min,hw_max,tof_offset,startTime,endTime)
    - DoMask(DAT)
    - ILambdaCorrDNA(dat,ec)
    - SolidAngleCorrDNA(dat)
    - CreateQEMap(dat,startQ,endQ,deltaQ)

    @param runNo        (int) Run Number
    @param HwParam      (string)
    @param LambParam    (string)
    @param QParam       (string)
    @param TimeParam    (string)
    @param initFile     (string)
    @param fileTag      (string)   
    @retval ECM      (ElementContainerMatrix)
    """

    if outputData !="QE" and outputData !="HW" and outputData !="TOF" and outputData !="MON":
      print("outputData column : QE or HW or TOF or MON")
      return

    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile) 

    useT0ModCorr      = SearchInitParamBool("useT0ModCorr",filepath)
    useMonEff         = SearchInitParamBool("useMonEff",filepath)
    useILambdaCorr    = SearchInitParamBool("useILambdaCorr",filepath)
    useMonNormalCorr  = SearchInitParamBool("useMonNormalCorr",filepath)
    useProtonNormCorr = SearchInitParamBool("useProtonNormCorr",filepath)
    useSolidAngleCorr = SearchInitParamBool("useSolidAngleCorr",filepath)
    useDetEff         = SearchInitParamBool("useDetEff",filepath)
    useAbsoCorr       = SearchInitParamBool("useAbsoCorr",filepath)
    useEffCorr        = SearchInitParamBool("useEffCorr",filepath)
    useFileOutput     = SearchInitParamBool("useFileOutput",filepath)
    filename          = SearchInitParamString("MASKfilename",filepath)
    laticetype        = SearchInitParamString("laticetype",filepath)
    sampletype        = SearchInitParamString("sampletype",filepath)
    sampleDataFile    = SearchInitParamString("sampleDataFile",filepath)
    factor            = float(SearchInitParamString("factor",filepath))
    t0_offset         = float(SearchInitParamString("t0_offset",filepath))
    background        = float(SearchInitParamString("background",filepath))
    #T. Yamada Add [121129]
    UseFastChopper    = SearchInitParamBool("UseFastChopper",filepath)
    #T. Yamada End [121129]

    useEiConv = True

    QParamList = QParam.split(",")
    if len(QParamList)==3:
            startQ = float(QParamList[0])
            endQ = float(QParamList[1])
            deltaQ = float(QParamList[2])
    else:
            startQ = 0.0
            endQ = 3.0
            deltaQ = 0.05
    if outputData != "MON":
        if outputData == "TOF":
           #DAT = BaseComDNA.GetHistogram(runNo,0,-1,-1,-1,-1,-1,100) T. Yamada comment out [121129]
           DAT = Cmm.GetHistogram(runNo,0,-1,-1,-1,-1,-1,120)
           return DAT
        if laticetype == "111":
           DAT = Cmm.GetHistogramHW(runNo,HwParam,LambParam,t0_offset,useT0ModCorr,TimeParam,tofOffsetFile="dummy", UseFastChopper=UseFastChopper, isHistogram=False)
           #print "TY->>", runNo,HwParam,LambParam,t0_offset,useT0ModCorr,TimeParam,UseFastChopper
           #ectemp = DAT.Put(60).Put(60)
           #ylist = ectemp.PutYList()
           #print ylist
        elif laticetype == "333":
           #DAT = BaseComDNA.GetHistogramHW333(runNo,HwParam,LambParam,t0_offset,useT0ModCorr,TimeParam) T. Yamada comment out[121129]
           DAT = CmmGetHistogramHW333(runNo,HwParam,LambParam,t0_offset,useT0ModCorr,TimeParam,UseFastChopper=UseFastChopper)
        else:
           return
        if outputData == "HW":
           return DAT
        Cmm.DoMask(DAT, filename)
        #BaseComDNA.DoMask(DAT, filename)
    #EC = BaseComDNA.GetMonHistogram(runNo,useEiConv,LambParam,t0_offset,background,useT0ModCorr,TimeParam) T. Yamada comment out
    if useMonEff:
        EC = Cmm.GetHistogramMon(runNo,useEiConv,LambParam,t0_offset,background,useT0ModCorr,TimeParam,UseFastChopper=UseFastChopper, isHistogram=False)
        BaseComDNA.MutiplyConstant(EC,factor)

    if outputData == "MON":
        return EC


    if useMonNormalCorr:
        SumEC = sum(EC.PutY())
        """
        #T. Yamada comment out [121129]
        BaseComDNA.MutiplyConstant(DAT,1/SumEC/factor)
        print "Monitor Normalize factor * factor =",SumEC*factor
        """
        
        if (SumEC == 0.0): #T.Yamada Add [130518]
            SumEC = 1
            
        BaseComDNA.MutiplyConstant(DAT,1/SumEC)
        print("Monitor Normalize factor =",SumEC)

    if useProtonNormCorr:
        Cmm.NormByBeamCurrent(DAT,factor,offset_sec=0.0,isCT8n=True)

    if useILambdaCorr:
        ECM = Cmm.ILambdaCorrDNA(DAT, EC, useMonEff)
    else:
        ECM = DAT

    if useSolidAngleCorr:
        ECM2 = Cmm.SolidAngleCorrDNA(ECM, useDetEff, useAbsoCorr,useEffCorr,sampletype,sampleDataFile)
    else:
        ECM2 = ECM
    ECA = Cmm.CreateQEMap(ECM2,startQ,endQ,deltaQ)
    #ectemp = ECA.Put(7)
    #ylist = ectemp.PutYList()
    #print ylist

    if useMonNormalCorr: #T.Yamada Add[130520]
        HH = ECA.PutHeaderPointer()
        HH.OverWrite("MONITORCOUNT",SumEC)

    if useFileOutput:
        if (fileTag=="_"):
            BaseComDNA.OutputECA(ECA, "_"+outputData)
            BaseComDNA.OutputECAText(ECA, "_"+outputData)
        else:
            BaseComDNA.OutputECA(ECA, "_"+outputData+"_"+fileTag)
            BaseComDNA.OutputECAText(ECA, "_"+outputData+"_"+fileTag)

    return ECA

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

def GetMeasurementTime(runNo=314):
    """
    @param runNo              (int)
    @retval starttime,endtime (tuple)
    """
    runnum=str(runNo).zfill(6)

    tt = mu.T0TreatToolsPsd()
    datapath=os.environ["MLF_DATA_DIR"]
    tmppath=os.path.join("/data","tmp")
    blname=os.environ["XXX"]
    edbfile=[]
    t0bfile=[]

    dirs=glob.glob(os.path.join(datapath,blname)+runnum+"*")
    footer = "_000.edb"
    files=glob.glob(dirs[0]+"/"+blname+runnum+"*"+footer)
    basefile = ((files[0].split("/"))[-1].split(footer))[0]
    basefiles = files=glob.glob(os.path.join(dirs[0],basefile)+"*.edb")

    for i in range(len(basefiles)):
        filenum=str(i).zfill(3)
        edbfile.append(os.path.join(dirs[0])+"/"+basefile +"_"+ str(filenum) +".edb")
        t0bfile.append(os.path.join(tmppath)+"/"+basefile +"_"+ str(filenum) +".t0b")
        tt.readOrgEvent(edbfile[i])
        tt.saveT0IndexEvent(t0bfile[i])
        tt.readT0IndexEvent(t0bfile[i])

    dt=tt.putT0ClockRegion()

    return str(dt[0]),str(dt[1])

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

def GetQETimeECM(runNo=314,HwParam=" ",LambParam=" ",QParam=" ",TimeParam=" ",initFile="GetQEDataOfDNA.ini",search_dir=""):
    """
    Elastic Scan (DNA), Get Time dependent QE Map Data
    - DoQEMask
    - SliceQEall
    - ElasticScanGetIntegral
    - ElasticScanAxisChange

    @param ECA          (ElementContainer)
    @param QParam       (string)
    @param HwParam    (string)
    @retval ECM      (ElementContainerMatrix)
    """
    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile)

    useFileOutput     = SearchInitParamBool("useFileOutput",filepath)
    os.system("cat /usr/local/mlf/DNA/ana/xml/ESAnaEnd.log.1 > /usr/local/mlf/DNA/ana/xml/ESAnaEnd.log")
    start = datetime.datetime.today()
    ECM = mm.ElementContainerMatrix()
    hh2=ECM.PutHeader()
    hh2.Add("RUNNUMBER",runNo)
    ECM.InputHeader(hh2)
    TimeParamList = TimeParam.split(",")

    ## append 20121115 AS.Y.Miyashita -start
    if float(TimeParamList[0])<0:
        endtime = TimeParamList[1]
        deltatime = TimeParamList[2]
        TimeParamList=["0",endtime,deltatime]

    if float(TimeParamList[1])<0:
        measTime = GetMeasurementTime(runNo)
        starttime = TimeParamList[0]
        deltatime = TimeParamList[2]
        TimeParamList=[starttime,measTime[1],deltatime]
    ## append 20121115 AS.Y.Miyashita -end
    
    NumOfTimeParam = math.ceil((float(TimeParamList[1]) - float(TimeParamList[0]))/float(TimeParamList[2]))
    for i in range(int(NumOfTimeParam)):
        f = open("/usr/local/mlf/DNA/ana/xml/ESAnaEnd.log","r")
        EndFlug = f.readlines()
        if EndFlug[0]=="0\n":
              return ECM
        print("")
        print(">>>>>>>>  ",i,"/",int(NumOfTimeParam),"  <<<<<<<<")
        print("")
        startTime = str(float(TimeParamList[0])+float(TimeParamList[2])*i)
        endTime = str(float(TimeParamList[0])+float(TimeParamList[2])*(i+1))
        TimeParamI = startTime + "," + endTime
        ECA = GetDataOfDNA(runNo,HwParam,LambParam,QParam,TimeParamI,initFile,"QE",str(i),search_dir)
        hh=ECA.PutHeader()
        hh.Add("StartTime",startTime)
        hh.Add("EndTime",endTime)
        ECA.InputHeader(hh)
        ECM.Add(ECA)

    if useFileOutput:
        BaseComDNA.OutputECM(ECM,"_ES")

    print("")
    print("start time \t: ",start)
    print("end time \t: ",datetime.datetime.today())
    print("")
    print(">>>>>>>>  end  <<<<<<<<")
    print("")

    return ECM

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

def ElasticScanQ2LnI(ecm=DAT,HwParam=" ",QParam=" ",initFile="GetQEDataOfDNA.ini",search_dir=""):
    """
    Elastic Scan (DNA), QE ElementContainer Data to Slice Q Intensity Data
    - DoQEMask
    - SliceQEall
    - ElasticScanGetIntegral
    - ElasticScanAxisChange

    @param ECM          (ElementContainerMatrix)
    @param HwParam      (string)
    @param QParam       (string)
    @param initFile     (string)
    @param search_dir   (string)
    @retval ECA      (ElementContainerArray)
    """
    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile)
    print("sss",filepath)
    QEfilename          = SearchInitParamString("QEfilename",filepath)

    QParamList = QParam.split(",")
    startQ = float(QParamList[0])
    endQ = float(QParamList[1])
    deltaQ = float(QParamList[2])

    EParamList = HwParam.split(",")
    startE = float(EParamList[0])
    endE = float(EParamList[1])

    num_of_eca = ecm.PutTableSize()
    ec0 = mm.ElementContainer()
    ECA = mm.ElementContainerArray()
    start = datetime.datetime.today()
    print(">>>>>>>>  start  <<<<<<<<")
    hhm = ecm.PutHeader()
    runNo=0
    if(hhm.CheckKey("RUNNUMBER")==1):
       runNo = hhm.PutString("RUNNUMBER")

    for i in range(num_of_eca):
        if ((i+1)%10)==0:
            print(">>>     ",i+1,"/",num_of_eca,"     <<<")
        eca = ecm(i)
        hh=eca.PutHeader()
        if(hh.CheckKey("RUNNUMBER")==0):
           hh.Add("RUNNUMBER",runNo)

        BaseComDNA.DoQEMask(eca, QEfilename)


        eca1 = BaseComDNA.SliceQEall(eca, startQ, endQ, deltaQ)

        ec = ElasticScanGetIntegral(eca1, startE, endE)
        ec1 = ElasticScanAxisChange(ec)
        if (i==0):
           ec0 = ec1
###[TY20240221]
#        elif(i!=0):
#           ec2 = ElasticScanLnNormalize(ec1,ec0)
#           if ((i==115)or(i==116)):
#               print("@@@@", i)
#               ec2.Dump()
#           else:
#               pass
#           ec3 = ElasticScanMaskedQData(ec2)
#           ec3.InputHeader(hh)
#           ECA.Add(ec3)
###[TY20240221]
        ec2 = ElasticScanLnNormalize(ec1,ec0)
        ec3 = ElasticScanMaskedQData(ec2)
        ec3.InputHeader(hh)
        ECA.Add(ec3)

    print("")
    print("start time \t: ",start)
    print("end time \t: ",datetime.datetime.today())
    print("")
    print(">>>>>>>>  end  <<<<<<<<")
    print("")

    return ECA

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

def ElasticScanQ2LnIExt(ecm=DAT,ecaN=ECA,factor=1.0,HwParam=" ",QParam=" ",initFile="GetQEDataOfDNA.ini",search_dir=""):
    """
    Elastic Scan (DNA), QE ElementContainer Data to Slice Q Intensity Data
    - DoQEMask
    - SliceQEall
    - ElasticScanGetIntegral
    - ElasticScanAxisChange

    @param ecm       (ElementContainerMatrix)
    @param ecaN      (ElementContainerArray)
    @param factor    (float)
    @param HwParam   (string)
    @param QParam    (string)
    @retval ECA      (ElementContainerArray)
    """
    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile)
    QEfilename          = SearchInitParamString("QEfilename",filepath)

    QParamList = QParam.split(",")
    startQ = float(QParamList[0])
    endQ = float(QParamList[1])
    deltaQ = float(QParamList[2])

    EParamList = HwParam.split(",")
    startE = float(EParamList[0])
    endE = float(EParamList[1])

    num_of_eca = ecm.PutTableSize()
    ec0 = mm.ElementContainer()
    ECA = mm.ElementContainerArray()
    start = datetime.datetime.today()
    print(">>>>>>>>  start  <<<<<<<<")

    hhm = ecm.PutHeader()
    runNo=0
    if(hhm.CheckKey("RUNNUMBER")==1):
       runNo = hhm.PutString("RUNNUMBER")

    BaseComDNA.DoQEMask(ecaN, QEfilename)
    ecaN1 = BaseComDNA.SliceQEall(ecaN, startQ, endQ, deltaQ)
    ecN = ElasticScanGetIntegral(ecaN1, startE, endE)
    ecN1 = ElasticScanAxisChange(ecN)
    ecN1.MulMySelf(factor)

    for i in range(num_of_eca):
        if ((i+1)%10)==0:
            print(">>>     ",i+1,"/",num_of_eca,"     <<<")
        eca = ecm(i)
        hh=eca.PutHeader()
        if(hh.CheckKey("RUNNUMBER")==0):
           hh.Add("RUNNUMBER",runNo)
        BaseComDNA.DoQEMask(eca, QEfilename)
        eca1 = BaseComDNA.SliceQEall(eca, startQ, endQ, deltaQ)
        ec = ElasticScanGetIntegral(eca1, startE, endE)
        ec1 = ElasticScanAxisChange(ec)

        ec2 = ElasticScanLnNormalize(ec1,ecN1)
        ec3 = ElasticScanMaskedQData(ec2)
        ec3.InputHeader(hh)
        ECA.Add(ec3)

    print("")
    print("start time \t: ",start)
    print("end time \t: ",datetime.datetime.today())
    print("")
    print(">>>>>>>>  end  <<<<<<<<")
    print("")

    return ECA

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


def ElasticScanTotalIntensity(ecm=DAT,HwParam=" ",QParam=" ",initFile="GetQEDataOfDNA.ini",search_dir=""):
    """
    Elastic Scan (DNA), Time dependent of Total Intensity
    - DoQEMask
    - SliceQEall
    - ElasticScanGetIntegral
    - ElasticScanAxisChange

    @param ECM       (ElementContainerMatrix)
    @param HwParam    (string)
    @param QParam    (string)
    @retval EC       (ElementContainer)
    """
    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile)
    QEfilename          = SearchInitParamString("QEfilename",filepath)

    QParamList = QParam.split(",")
    startQ = float(QParamList[0])
    endQ = float(QParamList[1])
    deltaQ = float(QParamList[2])

    EParamList = HwParam.split(",")
    startE = float(EParamList[0])
    endE = float(EParamList[1])

    num_of_eca = ecm.PutTableSize()
    ECA = mm.ElementContainerArray()
    start = datetime.datetime.today()
    print(">>>>>>>>  start  <<<<<<<<")
    ECout = mm.ElementContainer()
    ECoutX = []
    ECoutY = []
    ECoutE = []

    hhm = ecm.PutHeader()
    runNo=0
    if(hhm.CheckKey("RUNNUMBER")==1):
       runNo = hhm.PutString("RUNNUMBER")

    #for i in range(num_of_eca -1):[TY20240221]
    for i in range(num_of_eca):
        if ((i+1)%10)==0:
            print(">>>     ",i+1,"/",num_of_eca,"     <<<")
        #eca = ecm(i+1)[TY20240221]
        eca = ecm(i)
        hh=eca.PutHeader()
        BaseComDNA.DoQEMask(eca, QEfilename)
        eca1 = BaseComDNA.SliceQEall(eca, startQ, endQ, deltaQ)
        ec = ElasticScanGetIntegral(eca1, startE, endE)
        ecY = ec.PutY()
        ecE = ec.PutE()
        IntegralY =0
        IntegralE2 =0
        for j in range(len(ecY)):
            IntegralY = IntegralY + ecY[j]
            IntegralE2 = IntegralE2 +ecE[j]*ecE[j]
        IntegralE = math.sqrt(IntegralE2)
        ECoutY.append(IntegralY)
        ECoutE.append(IntegralE)
        if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
            st = hh.PutDouble("StartTime")
            et = hh.PutDouble("EndTime")
            ECoutX.append(st)
        else:
            ECoutX.append(i)
    if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
        ECoutX.append(et)
    else:
        ECoutX.append(num_of_eca)
        print("--------------")

    hhec = ECout.PutHeader()
    hhec.Add("RUNNUMBER",runNo)
    ECout.InputHeader(hhec)

    ECout.Add("time",ECoutX," Time - [sec] ")
    ECout.Add("intensity",ECoutY,' $\int \int$ I(Q,E)dQdE' )
    ECout.Add("error",ECoutE)
    ECout.SetKeys("time","intensity","error")
    print("")
    print("start time \t: ",start)
    print("end time \t: ",datetime.datetime.today())
    print("")
    print(">>>>>>>>  end  <<<<<<<<")
    print("")

    return ECout

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

def ElasticScanMaskedQData(ec):
    """
    """
    xbin = ec.PutX()
    ybin = ec.PutY()
    ebin = ec.PutE()
    xbin_center=[]

    for i in range(xbin.size()-1):
        xbin_center.append( (xbin[i]+xbin[i+1])*0.5 )

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

    for i in range(ebin.size()):
        if ebin[i]!=0:
            xbin_center_new.append(xbin_center[i])
            ybin_new.append(ybin[i])
            ebin_new.append(ebin[i])

    xbin_new.append(xbin[0])
    for i in range(len(xbin_center_new)):
        xbin_new.append(-xbin_new[i]+xbin_center_new[i]*2)

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

    return ec_out

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

def ElasticScanFit(eca=ECA,func="p1"):
    """
    Elastic Scan (DNA), Fitting loop

    @param ECA          (ElementContainerArray)
    @param func         (string)
    @retval DAT          (ElementContainer)
    """
    x_bin=[]
    y_bin=[]
    e_bin=[]

    num_of_ec = eca.PutSize()
    for i in range(num_of_ec):
        num_of_func = len(func.split(" "))
        ec = eca(i)
        if num_of_func==1:
            if (func == "c")or(func == "p1")or(func == "p2"):
                #param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0", "-10.0", "10.0", "0.0,3.0", False, 10000, False) #T.Yamada Comment out[130211]
                param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0", "-10.0", "10.0", "1","0.0,3.0", False, 10000, False) #T.Yamada[130211] T.Yamada add 1 as link_value [130228]
                #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0", "-10.0", "10.0", "0.0,3.0", False, 10000, True)
            else:
                print("Failed to set fitting function.")
                param_result=[0]
                param_result_error=[0]
        if num_of_func==2:
            flug1 = (func.split(" ")[0] == "c")or(func.split(" ")[0] == "p1")or(func.split(" ")[0] == "p2")
            flug2 = (func.split(" ")[1] == "c")or(func.split(" ")[1] == "p1")or(func.split(" ")[1] == "p2")
            if flug1 and flug2:
                param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0,0.0", "-10.0,-10.0", "10.0,10.0", "0.0,3.0", False, 10000, False)
                #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0,0.0", "-10.0,-10.0", "10.0,10.0", "0.0,3.0", False, 10000, True)
            else:
                print("Failed to set fitting function.")
                param_result=[0]
                param_result_error=[0]
        if num_of_func==3:
            flug1 = (func.split(" ")[0] == "c")or(func.split(" ")[0] == "p1")or(func.split(" ")[0] == "p2")
            flug2 = (func.split(" ")[1] == "c")or(func.split(" ")[1] == "p1")or(func.split(" ")[1] == "p2")
            flug3 = (func.split(" ")[2] == "c")or(func.split(" ")[2] == "p1")or(func.split(" ")[2] == "p2")
            if flug1 and flug2 and flug3:

                param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0,0.0,0.0", "-10.0,-10.0,-10.0", "10.0,10.0,10.0", "0.0,3.0", False, 10000, False)
                #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0,0.0,0.0", "-10.0,-10.0,-10.0", "10.0,10.0,10.0", "0.0,3.0", False, 10000, True)

            else:
                print("Failed to set fitting function.")
                param_result=[0]
                param_result_error=[0]

        y_bin.append(-1.5*float(param_result[0]))
        e_bin.append(1.5*float(param_result_error[0]))
        hh = ec.PutHeader()
        if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
            st = hh.PutDouble("StartTime")
            et = hh.PutDouble("EndTime")
        else:
            st = i
        x_bin.append(st)
        print("")
        print("ElasticScanFit >> Slope = ",param_result[0],", error = ",param_result_error[0]) 
        print("ElasticScanFit >> Chi square = ",chi)
        #print("ElasticScanFit >> ",i," / ",num_of_ec-1, " <<")
        print("ElasticScanFit >> ",i+1," / ",num_of_ec, " <<")
        print("")
    if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
        x_bin.append(et)
    else:
        x_bin.append(st)

    if(hh.CheckKey("RUNNUMBER")==1):
           runNo = hh.PutString("RUNNUMBER")

    EC = mm.ElementContainer()

    hhec = EC.PutHeader()
    hhec.Add("RUNNUMBER",runNo)

    EC.InputHeader(hhec)

    EC.Add("time",x_bin," Time - [sec] ")
    EC.Add("intensity",y_bin,' u$^{2}$ ')
    EC.Add("error",e_bin)
    EC.SetKeys("time","intensity","error")

    return EC
#########################################################################

def ElasticScanCheckTemp(ec=EC,temptype="Si"):
    """
    Elastic Scan (DNA), Temperature reading

    @param ec          (ElementContainer)
    @param temptype    (int)
    @retval EC         (ElementContainer)
    """
    hh = ec.PutHeader()
    if(hh.CheckKey("RUNNUMBER")==1):
       runNo = hh.PutInt4("RUNNUMBER")

    EC = mm.ElementContainer()
    XAxis = ec.PutX()
    YAxis = []
    EAxis = []
    for i in range(len(XAxis)-1):
        print("")
        print("ElasticScanCheckTemp >> ",i," / ",len(XAxis)-2, " <<")
        TimeParam = str(XAxis[i])+","+str(XAxis[i+1])
        print("TimeParam", TimeParam)
        startday,starttime,endday,endtime = BaseComDNA.CheckRealTime(runNo,TimeParam)
        print(startday,starttime,endday,endtime)
        #T.Yamada Add [121221]
        if (i==0):
            BaseComDNA.DownloadLogFile(startday,endday)
        #T.Yamada End [121221]
#        temp_result,ECresult = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype) #T. Yamada [130121]
        temp_result = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype,False)
#        YAxis.append(temp_result[(temptype-1)*5]) T. Yamada Comment Out [130118]
        YAxis.append(temp_result[0]) # T. Yamada Modified [130118]
        EAxis.append(0)

    EC.Add("xaxis",XAxis," Time - [sec] ")
    EC.Add("yaxis",YAxis," Temperature[K] ")
    EC.Add("eaxis",EAxis)
    EC.InputHeader(hh)
    EC.SetKeys("xaxis","yaxis","eaxis")

    return EC

#########################################################################
#T.Yamada
def ElasticScanCheckTempNew(ec=EC,temptype="Si"):
    """
    Elastic Scan (DNA), Temperature reading

    @param ec          (ElementContainer)
    @param temptype    (int)
    @retval EC         (ElementContainer)
    """
    hh = ec.PutHeader()
    if(hh.CheckKey("RUNNUMBER")==1):
       runNo = hh.PutInt4("RUNNUMBER")

    EC = mm.ElementContainer()
    XAxis = ec.PutX()
    YAxis = []
    EAxis = []
    dt = XAxis[1]-XAxis[0]
    TimeParam = str(XAxis[0])+","+str(XAxis[len(XAxis)-1]+dt*5)
    print(TimeParam)
    startday,starttime,endday,endtime = BaseComDNA.CheckRealTime(runNo,TimeParam)
    print(startday,starttime,endday,endtime)
    TKEC = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype,True)
    TK_X = TKEC.PutX()
    TK_Y = TKEC.PutY()
    print("TKCheck", TK_X[0],TK_X[len(TK_X)-1], XAxis[len(XAxis)-1])
    jj = 0
    ii = 0
    TKsum = 0
    TKtimeIntegrate=0
    for ii in range(len(XAxis)-1):
        TKtimeIntegrate=0.0
        TKSum = 0.0
        TKFlag = 0
        if jj<len(TK_Y):
            while 1:
                if TK_X[jj] < XAxis[ii] and jj<len(TK_Y):
                    jj += 1
                elif TK_X[jj]>=XAxis[ii] and TK_X[jj]<=XAxis[ii+1] and jj<len(TK_Y):
                    TKSum += TK_Y[jj]*(TK_X[jj+1]-TK_X[jj])
                    TKtimeIntegrate += (TK_X[jj+1]-TK_X[jj])
                    jj+=1
                    TKFlag += 1
                elif TK_X[jj] > XAxis[ii] and jj<len(TK_Y):
                    if (TKFlag != 0):        
                        YAxis.append(TKSum/TKtimeIntegrate)
                        EAxis.append(0)
                    #print "TCheck",TKSum,ii,jj
                    jj+=1
                    ii+=1
                    break
                else:
                    break

    print("Ylength", len(XAxis),len(YAxis), len(EAxis))
    EC.Add("xaxis",XAxis," Time - [sec] ")
    EC.Add("yaxis",YAxis," Temperature[K] ")
    EC.Add("eaxis",EAxis)
    EC.InputHeader(hh)
    EC.SetKeys("xaxis","yaxis","eaxis")

    return EC


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

def ElasticScanXAxisChangeToTemp(ec1,ec2,TempParam):
    """
    Elastic Scan (DNA), Fitting loop

    @param ec1          (ElementContainer)
    @param ec2          (ElementContainer)
    @param TempParam    (string)
    @retval EC          (ElementContainer)
    """
    TempParamList = TempParam.split(",")

    TempMin   = float(TempParamList[0])
    TempMax   = float(TempParamList[1])
    deltaTemp = float(TempParamList[2])

    YAxis1 = ec1.PutY()
    EAxis1 = ec1.PutE()

    YAxis2 = ec2.PutY()
    num_of_YAxis = len(YAxis2)

    SumY = []
    SumE2 = []
    AveX = []

    num_of_element = []
    DeltaTempFlug = False
    for j in range(num_of_YAxis-1):
        if deltaTemp < YAxis2[j+1]-YAxis2[j]:
            deltaTemp = YAxis2[j+1]-YAxis2[j]
            DeltaTempFlug = True

    deltaTemp = math.ceil(deltaTemp*10)/10

    if DeltaTempFlug:
        print("delta Temp parameter is too short.")
        print("delta Temp parameter is set ",deltaTemp,"[K]")
        print("If this value is not adequate, please change delta time parameter and re-calculate.")

    num_of_bin = int(math.ceil((TempMax - TempMin)/deltaTemp))

    for i in range(num_of_bin):
        num_of_element.append(0)
        SumY.append(0)
        SumE2.append(0)
###T. Yamada comment out [121207]
#        for j in range(num_of_YAxis):
#            if (YAxis2[j]>(TempMin+i*deltaTemp)) and (YAxis2[j]<=(TempMin+(i+1)*deltaTemp)):
#                num_of_element[i] = num_of_element[i] + 1
#                SumY[i] = SumY[i] + YAxis1[j]
#                SumE2[i] = SumE2[i] + EAxis1[j]*EAxis1[j]
###T. Yamada Modified. The source is from AS. [121207]
        threshold_val = 0.0001
        for j in range(num_of_YAxis):
            if abs(YAxis1[j]) > threshold_val:
                if (YAxis2[j]>(TempMin+i*deltaTemp)) and (YAxis2[j]<=(TempMin+(i+1)*deltaTemp)):
                    num_of_element[i] = num_of_element[i] + 1
                    SumY[i] = SumY[i] + YAxis1[j]
                    SumE2[i] = SumE2[i] + EAxis1[j]*EAxis1[j]
            else:
                pass
###T. Yamada End
        AveX.append(TempMin+i*deltaTemp)
    AveX.append(TempMin+num_of_bin*deltaTemp)
    AveY = []
    AveE = []
    dataflug = False

    for i in range(num_of_bin):
        if num_of_element[i] != 0:
            AveY.append(SumY[i]/num_of_element[i])
            AveE.append(math.sqrt(SumE2[i])/num_of_element[i])
            dataflug = True
        else:
            if dataflug:
                AveY.append(0)
                AveE.append(0)
            else:
                AveX.remove(AveX[0])

    EC = mm.ElementContainer()
    if len(AveY)!=0:
        EC.Add("Xaxis",AveX," Temperature[K] ")
        EC.Add("Yaxis",AveY,ec1.PutUnit(ec1.PutYKey()))
        EC.Add("Eaxis",AveE)

    else:
        EC.Add("Xaxis",[-1,1]," Temperature[K] ")
        EC.Add("Yaxis",[0],ec1.PutUnit(ec1.PutYKey()))
        EC.Add("Eaxis",[0])

    hh = ec1.PutHeader()
    EC.InputHeader(hh)

    EC.SetKeys("Xaxis","Yaxis","Eaxis")

    return EC

#########################################################################
def ElasticScanTimeToTempECM(ecm,TempParam,temptype):
    """
    Elastic Scan (DNA), Fitting loop
    @param ecm          (ElementContainerMatrix)
    @param TempParam    (string)
    @param temptype     (int)
    @retval ECM         (ElementContainerMatrix)
    """
    #ECMの段階で時間から温度のECMに変換。作成中, 温度情報を読むまで出来ている

    ECM = mm.ElementContainerMatrix()
    num_of_eca = ecm.PutTableSize()
    hhm = ecm.PutHeader()
    for i in range(num_of_eca):
        hh=eca.PutHeader()
        if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1) and (hhm.CheckKey("RUNNUMBER")==1):
            st = hh.PutDouble("StartTime")
            et = hh.PutDouble("EndTime")
            TimeParam = st + "," + et
            runNo = hhm.PutDouble("RUNNUMBER")
            startday,starttime,endday,endtime = BaseComDNA.CheckRealTime(runNo,TimeParam)
            BaseComDNA.DownloadLogFile(startday,endday)
            temp_result,ECresult = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype)
            temp_result = TM.CheckSampleTemp(startday,starttime,endday,endtime,temptype,False) # T.Yamada[130121]
            Temperature = temp_result[(temptype-1)*5]

        else:
            return ECM


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

def ElasticScanFitCheck(eca=ECA,time=100.0,func="p1"):
    """
    Elastic Scan (DNA), check Fit result

    @param ECA          (ElementContainerArray)
    @param time         (float)
    @param func         (string)
    @retval EC          (ElementContainer)

    """
    num = 0
    num_of_ec = eca.PutSize()
    for i in range(num_of_ec):
        ec=eca(i)
        hh = ec.PutHeader()
        if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
          if (time >= hh.PutDouble("StartTime")) and (time < hh.PutDouble("EndTime")):
              num = i

    num_of_func = len(func.split(" "))
    ec = eca(num)
    if num_of_func==1:
        if (func == "c")or(func == "p1")or(func == "p2"):
            param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0", "-10.0", "10.0", "0.0,3.0", False, 10000, False)
            #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0", "-10.0", "10.0", "0.0,3.0", False, 10000, False)
        else:
            print("Failed to set fitting function.")
            return
    if num_of_func==2:
        flug1 = (func.split(" ")[0] == "c")or(func.split(" ")[0] == "p1")or(func.split(" ")[0] == "p2")
        flug2 = (func.split(" ")[1] == "c")or(func.split(" ")[1] == "p1")or(func.split(" ")[1] == "p2")
        if flug1 and flug2:
            param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0,0.0", "-10.0,-10.0", "10.0,10.0", "0.0,3.0", False, 10000, False)
            #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0,0.0", "-10.0,-10.0", "10.0,10.0", "0.0,3.0", False, 10000, False)
        else:
            print("Failed to set fitting function.")
            return
    if num_of_func==3:
        flug1 = (func.split(" ")[0] == "c")or(func.split(" ")[0] == "p1")or(func.split(" ")[0] == "p2")
        flug2 = (func.split(" ")[1] == "c")or(func.split(" ")[1] == "p1")or(func.split(" ")[1] == "p2")
        flug3 = (func.split(" ")[2] == "c")or(func.split(" ")[2] == "p1")or(func.split(" ")[2] == "p2")
        if flug1 and flug2 and flug3:
            param_result,param_result_error,chi,result = PF.PeakFit(ec, func, "-1.0,0.0,0.0", "-10.0,-10.0,-10.0", "10.0,10.0,10.0", "0.0,3.0", False, 10000, False)
            #param_result,param_result_error,chi,result = PF.PeakFitNotUseWeight(ec, func, "-1.0,0.0,0.0", "-10.0,-10.0,-10.0", "10.0,10.0,10.0", "0.0,3.0", False, 10000, False)
        else:
            print("Failed to set fitting function.")
            return


    if (num == 0):
        print("Failed to get run-time-information.")
    print("slope = ",param_result[0],", error = ",param_result_error[0])
    print("chi square = ", chi)
    result.SetUnit(result.PutXKey(),' Q$^{2}$ [A$^{-1}$] ')
    result.SetUnit(result.PutYKey(),' ln [ I(t) / I$_{standard}$ ] ')

    return result

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

def ElasticScanDataCheck(eca=ECA,time=100.0):
    """
    Elastic Scan (DNA), check EC Data

    @param ECA          (ElementContainerArray)
    @param time         (float)
    @retval EC          (ElementContainer)

    """
    num = 0
    num_of_ec = eca.PutSize()
    for i in range(num_of_ec):
        ec=eca(i)
        hh = ec.PutHeader()
        if(hh.CheckKey("StartTime")==1) and (hh.CheckKey("EndTime")==1):
          if (time >= hh.PutDouble("StartTime")) and (time < hh.PutDouble("EndTime")):
              num = i
    if (num == 0):
        print("Failed to get run-time-information.")

    ec = eca(num)
    ec.SetUnit(ec.PutXKey(),' Q$^{2}$ [A$^{-1}$] ')
    ec.SetUnit(ec.PutYKey(),' ln [ I(t) / I$_{standard}$ ] ')

    return ec

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

def SearchInitParamBool(paramstring,filepath):
    f=open(filepath)
    lines = f.readlines()
    f.close()

    for line in lines:
        flug1 = re.search(paramstring, line)
        if flug1:
            if re.search("#", line):
                line = line.split("#")[0]
            flug2 = re.search("True",line)
            if flug2:
                print(paramstring,"\t: True")
                return True
            else:
                print(paramstring,"\t: False")
                return False

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

def SearchInitParamString(paramstring,filepath):
    f=open(filepath)
    lines = f.readlines()
    f.close()
    result =""
    for line in lines:
        flug1 = re.search(paramstring, line)
        if flug1:
            if re.search("#", line):
                line = line.split("#")[0]
            if re.search("\n", line):
                line = line.split("\n")[0]
            flug2 = re.search(" ", line)
            if flug2:
                linelist =line.split(" ")
                for i in range(len(linelist)):
                    if linelist[i]!="" and linelist[i]!=paramstring:
                         result = linelist[i]
                         print(paramstring,"\t:",result)
    return result

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


def ElasticScanGetIntegral(dat,emin,emax):
    """
    Elastic Scan

    @param dat     (ElementContaienrArray)
    @param emin    (double)
    @param emax    (double)
    @retval EC     (ElementContainer)
    """
    num_of_bin = dat.PutSize()
    Xbin = []
    Ybin = []
    Ebin = []

    """
    for i in range(num_of_bin):
       ec = dat(i)
       hh = ec.PutHeader()
       Xrange = hh.PutDoubleVector("XRANGE")
       sum_val,sum_val_e = PI.GetECPeakIntegral(ec,emin,emax)
       if (sum_val != sum_val):
           Ybin.append(0)
           Ebin.append(0)
       else:
           Ybin.append(sum_val)
           Ebin.append(sum_val_e)
       Xbin.append(Xrange[0])
    Xbin.append(Xrange[1])
    print "----"
    """
    xinitial=dat(0).PutHeader().PutDoubleVector("XRANGE")
    xbuf = xinitial[0]
    Xbin.append(xbuf)

    for i in range(num_of_bin):
       ec = dat(i)
       hh = ec.PutHeader()
       Xrange = hh.PutDoubleVector("XRANGE")
       dX=(Xrange[1]-Xrange[0])
       XCenter=dX*0.5+Xrange[0]

       sum_val,sum_val_e = PI.GetECPeakIntegral(ec,emin,emax)

       if (sum_val == sum_val):
           xbuf=xbuf + (XCenter-xbuf)*2
           Xbin.append(xbuf)
           Ybin.append(sum_val)
           Ebin.append(sum_val_e)

    EC = mm.ElementContainer()
    EC.Add("x",Xbin)
    EC.Add("y",Ybin)
    EC.Add("e",Ebin)
    EC.SetKeys("x","y","e")
    
    return EC

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

def ElasticScanAxisChange(ec):
    """
    Elastic Scan

    @param ec     (ElementContaienr)
    @retval EC     (ElementContainer)
    """

    Xbin = ec.PutX()

    xbuf = 0
    XbinNew = []
    XbinNew.append(xbuf)

    for i in range(len(Xbin)-1):
       XCenter = (Xbin[i]+Xbin[i+1])*0.5
       XCenter2 = XCenter**2
       xbuf=xbuf + (XCenter2-xbuf)*2
       XbinNew.append(xbuf)

    EC = mm.ElementContainer()
    EC.Add("x",XbinNew)
    EC.Add("y",ec.PutY())
    EC.Add("e",ec.PutE())
    EC.SetKeys("x","y","e")

    return EC

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

def ElasticScanAxisChange2(ec):
    """
    Elastic Scan

    @param ec     (ElementContaienr)
    @retval EC     (ElementContainer)
    """

    Xbin = ec.PutX()
    Ybin = ec.PutY()
    Ebin = ec.PutE()

    xbuf = 0
    XbinNew = []
    XbinNew.append(xbuf)
    XbinCenter2list = []

    YbinNorm = []
    EbinNorm = []

    for i in range(len(Xbin)-1):
       XCenter = (Xbin[i]+Xbin[i+1])*0.5
       XCenter2 = XCenter**2
       xbuf=xbuf + (XCenter2-xbuf)*2
       XbinNew.append(xbuf)
       XbinCenter2list.append(XCenter2)

    for i in range(len(Ybin)):
        YbinNorm.append(Ybin[i]/XbinCenter2list[i])
        EbinNorm.append(Ebin[i]/XbinCenter2list[i])

    EC = mm.ElementContainer()
    EC.Add("x",XbinNew)
    EC.Add("y",YbinNorm)
    EC.Add("e",EbinNorm)
    EC.SetKeys("x","y","e")

    return EC

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

def ElasticScanLnNormalize(ec,ec0):
    """
    Elastic Scan

    @param ec     (ElementContaienr)
    @param ec0     (ElementContaienr)
    @retval EC     (ElementContainer)
    """

    Xbin = ec.PutX()
    Xbin0 = ec0.PutX()
    Ybin = ec.PutY()
    Ybin0 = ec0.PutY()
    Ebin = ec.PutE()
    Ebin0 = ec0.PutE()

    XbinN = []
    YbinN = []
    EbinN = []

    #p=mp.MPlot(ec0)

    if(len(Xbin)!=len(Xbin0)) or ((Xbin[1])!=(Xbin0[1])):
        print("default-EC-Xbin and input-EC-Xbin are different. normalize was not performed.")

#####  2012/11/14 As.Y.Miyashita zero/division log(zero) treatment
#        for i in range(len(Xbin)-1):
#           XbinN.append(Xbin[i])
#           YbinN.append(math.log(Ybin[i]))
#           EbinN.append(Ebin[i]/Ybin[i])
#        XbinN.append(Xbin[len(Xbin)-1])
#
######
        XbinN.append(Xbin[0])
        for i in range(len(Xbin)-1):
           if Ybin[i]!=0:
               XbinN.append(-XbinN[-1]+Xbin[i]*2)
               YbinN.append(math.log(Ybin[i]))
               EbinN.append(Ebin[i]/Ybin[i])
        else:
            pass
###### 2012/11/14 As.Y.Miyashita zero/division log(zero) treatment
#    else:
#        for i in range(len(Xbin)-1):
#           XbinN.append(Xbin[i])
#           if Ybin0[i] !=0:
#               YbinN.append(math.log(Ybin[i]/Ybin0[i]))
#           else:
#               YbinN.append(0)
#           if Ybin0[i] !=0 and Ybin[i] !=0:
#               EbinN.append(Ebin[i]/Ybin[i]+Ebin0[i]/Ybin0[i])
#           else:
#               EbinN.append(0)
#        XbinN.append(Xbin[len(Xbin)-1])
######
    else:
        XbinN.append(Xbin[0])
        for i in range(len(Xbin)-1):
           if Ybin0[i] !=0 and Ybin[i] !=0:
               XbinN.append(-XbinN[-1]+Xbin[i]*2)
               YbinN.append(math.log(Ybin[i]/Ybin0[i]))
               EbinN.append(Ebin[i]/Ybin[i]+Ebin0[i]/Ybin0[i])
           else:
               pass
###T. Yamada Comment out [121207]
#    EC = mm.ElementContainer()
#    EC.Add("x",XbinN)
#    EC.Add("y",YbinN)
#    EC.Add("e",EbinN)
#    EC.SetKeys("x","y","e")
####

###T. Yamada Start [121207] This source is from AS.
    EC = mm.ElementContainer()
    XbinMinimum =3
    if len(XbinN)<=XbinMinimum:
        EC.Add("x",list(range(11))) #[20240222 TY] range(11) -> list(range(11))
        EC.Add("y",[0]*10)
        EC.Add("e",[1]*10)
        print("koko")
    else:
        EC.Add("x",XbinN)
        EC.Add("y",YbinN)
        EC.Add("e",EbinN)

    EC.SetKeys("x","y","e")
###T. Yamada End

    return EC

##########################################
def OutputECText(ec,basepath,filename):
    """
    @param ec      (ElementContainer)
    @param filename          (string)
    @param basepath          (string)
    @retval None
    """

    filenameECbin = os.path.join(basepath,filename)

    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 ReadECM(basepath,filename):
    """
    @param filename  (string)

    @retval ecm      (ElementContainerMatrix)
    """

    filenameECbin = os.path.join(basepath,filename)
    flug = os.path.exists(filenameECbin)
    print(basepath,filename) 
    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 OutputECM(ecm,basepath,filename):
    """
    @param ecm      (ElementContainerMatrix)
    @param basepath      (string)
    @param filename      (string)
    @retval None
    """
    filenameECbin = os.path.join(basepath,filename)

    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 GetQETimeECMMulthMain(runNo=314,HwParam=" ",LambParam=" ",QParam=" ",TimeParam=" ",initFile="GetQEDataOfDNA.ini",search_dir="",Multh=True):
    """
    Elastic Scan (DNA), Get Time dependent QE Map Data
    - DoQEMask
    - SliceQEall
    - ElasticScanGetIntegral
    - ElasticScanAxisChange

    @param ECA          (ElementContainer)
    @param QParam       (string)
    @param HwParam    (string)
    @retval ECM      (ElementContainerMatrix)
    """
    #search_dir="/home/dnaadmin/ana/setup"
    filepath =os.path.join(search_dir,initFile)

    useFileOutput     = SearchInitParamBool("useFileOutput",filepath)
    #os.system("cat /usr/local/mlf/DNA/ana/xml/ESAnaEnd.log.1 > /usr/local/mlf/DNA/ana/xml/ESAnaEnd.log")
    start = datetime.datetime.today()
    ECM = mm.ElementContainerMatrix()
    hh2=ECM.PutHeader()
    hh2.Add("RUNNUMBER",runNo)
    ECM.InputHeader(hh2)
    TimeParamList = TimeParam.split(",")

    ## append 20121115 AS.Y.Miyashita -start
    if float(TimeParamList[0])<0:
        endtime = TimeParamList[1]
        deltatime = TimeParamList[2]
        TimeParamList=["0",endtime,deltatime]

    if float(TimeParamList[1])<0:
        measTime = GetMeasurementTime(runNo)
        starttime = TimeParamList[0]
        deltatime = TimeParamList[2]
        TimeParamList=[starttime,measTime[1],deltatime]
    ## append 20121115 AS.Y.Miyashita -end
    
    NumOfTimeParam = math.ceil((float(TimeParamList[1]) - float(TimeParamList[0]))/float(TimeParamList[2]))
    for i in range(int(NumOfTimeParam)):
        #f = open("/usr/local/mlf/DNA/ana/xml/ESAnaEnd.log","r")
        #EndFlug = f.readlines()
        #if EndFlug[0]=="0\n":
        #    print "AAAAAAAA"
        #    return ECM
        print("")
        print(">>>>>>>>  ",i,"/",int(NumOfTimeParam),"  <<<<<<<<")
        print("")
        startTime = str(float(TimeParamList[0])+float(TimeParamList[2])*i)
        endTime = str(float(TimeParamList[0])+float(TimeParamList[2])*(i+1))
        TimeParamI = startTime + "," + endTime
        ECA = GetDataOfDNA(runNo,HwParam,LambParam,QParam,TimeParamI,initFile,"QE",str(i),search_dir)
        hh=ECA.PutHeader()
        hh.Add("StartTime",startTime)
        hh.Add("EndTime",endTime)
        ECA.InputHeader(hh)
        ECM.Add(ECA)

    BaseComDNA.OutputECM(ECM,"_"+TimeParamList[0]+"_ES")

    print("")
    print("start time \t: ",start)
    print("end time \t: ",datetime.datetime.today())
    print("")
    print(">>>>>>>>  end  <<<<<<<<")
    print("")

    return ECM

#########################################
#T.Yamada [130323]
def ElasticScanOutPut(ecm):
    #dataPath = "/home/dnaadmin/DNA/tmp/"
    #dataPath = os.path.join( os.environ["UTSUSEMI_USR_PRIV_HOME"],"DNA","tmp" )
    dataPath = os.path.join( mu.UtsusemiEnvGetUserDir(),"DNA","tmp" )
    SaveString = ""
    for ii in range(ecm.PutTableSize()):
        if ii%10 == 0:
            print("%d / %d is started" %(ii,ecm.PutTableSize()))
        eca = ecm.Put(ii)
        IQElastic = []
        IQElasticSD = []
        Q = []
        for jj in range(eca.PutTableSize()):
            ec = eca.Put(jj)
            SQlist = ec.PutY()
            SQSDlist = ec.PutE()
            IQ = 0
            IQSD = 0
            Qtemp = []
            for kk in range(len(SQlist)):
                IQ += SQlist[kk]
                IQSD += SQSDlist[kk]*SQSDlist[kk]
                Qtemp = list(ec.PutHeader().PutDoubleVector("XRANGE"))
            IQElastic.append(IQ)
            IQElasticSD.append(math.sqrt(IQSD))
            Q.append((Qtemp[0]+Qtemp[1])/2)
       
        st = float(eca.PutHeader().PutString("StartTime"))
        et = float(eca.PutHeader().PutString("EndTime"))
        SaveString += "########\n"
        SaveString += "%f\n" %((st+et)/2)
       
        for jj in range(len(IQElastic)):
            #SaveString += "%f,%f,%f\n" %((Q[jj],IQElastic[jj],math.sqrt(IQElasticSD[jj])))
            SaveString += "%f,%f,%f\n" %((Q[jj],IQElastic[jj],IQElasticSD[jj]))

    RunNo = ecm.PutHeader().PutString("RUNNUMBER")
    filename = dataPath+"/Run"+RunNo+"IQ.txt"
    fo = open (filename, "w")
    fo.write(SaveString)
    fo.close
    print("output >>", filename)
#T.Yamada End
#############################################


# Dictionary for entry the name of functions
_functions = {
               "GetDataOfDNA":GetDataOfDNA,
               "ElasticScanQ2LnI":ElasticScanQ2LnI,
               "ElasticScanQ2LnIExt":ElasticScanQ2LnIExt,
               "ElasticScanFit":ElasticScanFit,
               "ElasticScanFitCheck":ElasticScanFitCheck,
               "ElasticScanDataCheck":ElasticScanDataCheck,
               "ElasticScanTotalIntensity":ElasticScanTotalIntensity,
               "ElasticScanCheckTemp":ElasticScanCheckTemp,
               "ElasticScanXAxisChangeToTemp":ElasticScanXAxisChangeToTemp,

               "GetQETimeECM":GetQETimeECM
             }
         
