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

from __future__ import print_function
import os
import Manyo as mm
import Manyo.Utsusemi as mu
import utsusemi.DNA.ana.Reduction.EditWiringFile as ED

import utsusemi.DNA.ana.Reduction.EventDataToEcm as EtoE
import sys,shutil
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
    from elementtree.ElementTree import Element
else:
    from xml.etree.ElementTree import ElementTree
    from xml.etree.ElementTree import Element
try:
    ver_ED = float( ED.__version__ )
    if (ver_ED<0.6):
        raise UserWarning("EditDetectorInfo or EventDataToHist is not valid.")
except:
    raise UserWarning("EditDetectorInfo or EventDataToHist is not valid.")

__version__ = '0.6'

class Histogram(object):
    """
    Load EventData and convert to histogram.
    ver 0.6 [130304] update for Monitor
    ver 0.5 [130213] upgrade
    ver 0.4 [110717] replace EventDataToHist to EventDataToEcm
    ver 0.3 [110104] add control tofDoubleFrameBoundary
    ver 0.2 [101108] can use direct conversion from event data to energy transfer
    ver 0.1 before 101108 original version
    """
    __version__ = '0.5'
    def __init__(self,runNo=-1,
                 ConvType=-1,
                 Params=[],
                 DetRange=[],
                 pixelNo=-1,
                 TimeRange=[],
                 envFile="environ_ana.xml",
                 frameInfo=[0,0.0],
                 DetType="PSD",
                 useTrignet=0,
                 isPulseHeight=False,
                 isDebug=False,
                 t0_offset="0.0",# AS add [t0_offset] 20140522 for DNA
                 tofOffsetFile="",
                 tofSource="0.0,400.0",
                 chopperFrequency=225,
                 isHistogram=True #[inamura 170616]
                ): 
        """
        Constructor and initialization
        
        @param runNo    (int) Run Number 0:Dummy data
        @param ConvType (int) TOF Conversion Type
        @param Params ([])
        @param DetRange ([])  [first PSD ID, final PSD ID]
        @param pixelNo  (int) the number of pixels on one PSD
        @param TimeRange ([]) [startTime, endTime] [seconds]
        @param envFile  (string) Environ file for event data to histogram
        @param frameInfo ([int,double]) FrameNo and Boundary TOF
        @param DetType  (string) PSD or N2MON
        @param isPulseHeight (bool)
        @param isDebug  (bool)
        @param t0_offset(str)
        """

        self.isParallel = False
        self.runNo = runNo
        self.ConvType = ConvType
        
        self.lambda_Center=-1.0 ##[inamura 170612]
        self.lambda_Delta=-1.0  ##[inamura 170612]
        isBadParams = False
        if ((self.ConvType==2) or (self.ConvType==3) or (self.ConvType==12) or (self.ConvType==13) or (self.ConvType==21)):
            if len(Params)<3:
                isBadParams = True
            ##[inamura 170612]-->
            if len(Params)==5:
                self.lambda_Center=Params[3]
                self.lambda_Delta=Params[4]
            ##<--[inamura 170612]
            Params = Params[:3]
        if (self.ConvType==20):
            if len(Params)<5:
                isBadParams = True
            Params = Params[:5]
        if (self.ConvType==22):
            if len(Params)<6:
                isBadParams = True
            Params = Params[:6]
        if isBadParams:
            msg = "Num of Parameters is invalid for type=%d ("
            for p in Params:
                msg += " %f" % (p)
            msg +=")"
            raise UserWarning(msg)

        print("koko94 Params", Params)
        self.Params = Params
        self.startDet = DetRange[0]
        self.endDet = DetRange[1]
        self.numOfPixelOnDet = pixelNo
        if len(TimeRange)>=2:
            self.SliceEventStart = TimeRange[0]
            self.SliceEventEnd = TimeRange[1]
        else:
            self.SliceEventStart = -1.0
            self.SliceEventEnd = -1.0
        self.envFile = ""
        if envFile.find(",")==-1:
            self.envFile = envFile
        else:
            self.envFile = "environ_ana.xml"

        self.TOFOffsetFile = tofOffsetFile

        self.frameInfo = frameInfo
        self.DetType = DetType
        self.useTrignet = useTrignet
        self.isPulseHeight = isPulseHeight
        self.isHistogram = isHistogram
        self.isDebug = isDebug
        
        ##self.L1 = EtoE.Def_L1*1000.0 #[mm]
        self.L1 = -1.0
        self.T0shift = 0.0
        #self.instCode = os.environ["UTSUSEMI_SYS_NAME"]
        self.instCode = mu.UtsusemiEnvGetInstCode()
        self.CommentHead = "Histogram >>>"
        
        self.DetectorInfo = None
        ana_env = mu.UtsusemiAnaEnvironReader(self.envFile)
        self.param_files={"WiringInfo":"","DetectorInfo":""}
        if not ana_env._Status:
            print(self.CommentHead+"environ file ("+self.envFile+") is not existed.")
            self.envFile = ""
            self.anaEnv = None
            self.Status = -1
            return
        else:
            self.anaEnv = ana_env
            
            param_files = self.anaEnv.PutParamFiles(self.runNo)
            if param_files.size()<2:
                msg = "Run No is not suitable to choose WiringInfo from environ_ana.xml"
                raise UserWarning(msg)

            ind = envFile.find(",")
            if self.isDebug:
                print("---================ Check envFile=",envFile,"ind=",ind)
            if ind==-1:
                self.param_files["WiringInfo"]=param_files[0]
                self.param_files["DetectorInfo"]=param_files[1]
            else:
                if self.isDebug:
                    print("=================== Changed by envFile")
                self.param_files["WiringInfo"]=envFile[:ind]
                if envFile[(ind+1):]!="":
                    self.param_files["DetectorInfo"]=envFile[(ind+1):]
                else:
                    self.param_files["DetectorInfo"]=param_files[1]
                
            self.Status = 0
            #self.DetectorInfo = mu.UtsusemiDetectorInfoReader3HePsd( self.anaEnv.Info["PositioningFile"] )
            path_dfile = ""
            #if os.path.exists( self.anaEnv.Info["PositioningFile"] ):
            #    path_dfile = self.anaEnv.Info["PositioningFile"]
            #else:
            #    path_dfile = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",self.anaEnv.Info["PositioningFile"])
            #    if not os.path.exists( path_dfile ):
            #        self.Status = -1
            #        print "Cannot find DetectorInfo file "+self.anaEnv.Info["PositioningFile"]
            #        return

            # 20151202 start
            fname = self.param_files["DetectorInfo"][:-4]
            footer= self.param_files["DetectorInfo"][-4:]
            pid = str(os.getpid())

            if os.path.exists( fname+"_"+pid+footer ):
                path_dfile = fname+"_"+pid+footer
            else:
                #path_dfile = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",fname+"_"+pid+footer)
                path_dfile = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "xml",fname+"_"+pid+footer)
                if not os.path.exists( path_dfile ):
                    self.Status = -1
                    print("Cannot find DetectorInfo file "+self.param_files["DetectorInfo"])
                    return
            # 20151202 end
                
            #self.DetectorInfo = mu.UtsusemiDetectorInfoReader3HePsd( path_dfile )
            self.DetectorInfo = mu.DetectorInfoEditorNeunet( path_dfile )
            self.L1 = self.DetectorInfo.PutInstL1()

        if useTrignet>0:
            self.caseInfoFile     = "cfileFiltDNA.xml"

            #20151202 start
            #chopCondInfoOrgFile = "cfileChopDNA.xml"
            chopCondInfoOrgFile = "cfileChopDNA170612.xml" ##[inamura 170612]
            #cpath  = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",chopCondInfoOrgFile)
            cpath  = os.path.join(mu.UtsusemiEnvGetBaseDir(),self.instCode,"ana","xml",chopCondInfoOrgFile)
            fname  = chopCondInfoOrgFile[:-4]
            footer = chopCondInfoOrgFile[-4:]
            pid = str(os.getpid())

            self.chopCondInfoFile=fname+"_"+pid+footer
            #self.chopCondInfoFile = "cfileChopDNA.xml"
            #CCpath = os.path.join(os.environ["HOME"],"ana","xml",self.chopCondInfoFile)
            #CCpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",self.chopCondInfoFile)
            CCpath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",self.chopCondInfoFile)
            shutil.copy(cpath,CCpath)
            #20151202 end
            #----------------------------------------------------------
            def _getHeader(dpath):
                headStr=""
                if dpath!="":
                    head=open(dpath)
                    l=head.readline()
                    if l[:2]=="<?":headStr+=l
                    l=head.readline()
                    if l[:2]=="<!":headStr+=l

                return headStr
            #----------------------------------------------------------
            def _appendHeader(dpath,headStr):
                allline=open(dpath,"r").read()

                f = open(dpath,"w")
                f.write(headStr)
                for line in allline:f.write(line)
                f.close()
            #----------------------------------------------------------
            def _writeParam(val,dpath,params,att="",i=0):
                if dpath!="":
                    headStr=_getHeader(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)
                    valStr=str(val)

                    if att=="":
                        ele[i].text=valStr
                    else:
                        ele[i].set(att,valStr)
                    dom.write(dpath)
                    _appendHeader(dpath,headStr)
            #----------------------------------------------------------
            def _selectSlit(dpath,useTrignet,chopperFrequency=225):
                if dpath!="":
                    headStr=_getHeader(dpath)

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

                    ele = dom.getroot()

                    for e in ele.find("fastChopper").findall("slit"):
                        ele.find("fastChopper").remove(e)

                    slit3cm = zip(["0","1","2"],["90","180","270"],["5.73","5.73","5.73"])               ,"3"
                    slit1cm = zip(["0"],        ["0"],             ["1.91"])                             ,"1"
                    slitAll = zip(["0","1","2","3"],["0","90","180","270"],["1.91","5.73","5.73","5.73"]),"4"

                    if useTrignet==1 or useTrignet==4:
                        slitTags=slitAll
                    elif useTrignet==2 or useTrignet==5:
                        slitTags=slit1cm
                    elif useTrignet==3 or useTrignet==6:
                        slitTags=slit3cm

                    ele.find("fastChopper").set("n",slitTags[1])
                    ele.find("fastChopper").set("frequency",str(chopperFrequency))
                    for i,angle,width in slitTags[0]:
                        elem=Element("slit")
                        elem.set("i",i)
                        elem.set("angle",angle)
                        elem.set("width",width)
                        ele.find("fastChopper").append(elem)

                    dom.write(dpath)
                    _appendHeader(dpath,headStr)
            #----------------------------------------------------------

            ##[inamura 170612]-->
            _writeParam(str(self.lambda_Center),CCpath,["lambdaCenter"])
            _writeParam(str(self.lambda_Delta),CCpath,["lambdaDelta"])
            ##<--[inamura 170612]

            if useTrignet==1 or useTrignet==2 or useTrignet==3: # Use Trignet

                _selectSlit(CCpath,useTrignet,chopperFrequency)

                if "," in t0_offset:
                    offsets = t0_offset.split(",")
                elif  "/" in t0_offset:
                    offsets = t0_offset.split("/")
                else:
                    offsets = [t0_offset]
                try:
                    if len(offsets)==0:
                        tof_offset    = 0
                        tof_resolver1 = 0
                        tof_resolver2 = 0
                    elif len(offsets)==1:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = 0
                        tof_resolver2 = 0
                    elif len(offsets)==2:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = float(offsets[1])
                        tof_resolver2 = 0
                    elif len(offsets)>=3:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = float(offsets[1])
                        tof_resolver2 = float(offsets[2])
                except:
                    tof_offset    = 0
                    tof_resolver1 = 0
                    tof_resolver2 = 0

                _writeParam(str(tof_offset),CCpath,["tofOffset"])

                if DetType=="uPSD":
                    _writeParam(str(-tof_resolver1)+","+str(-tof_resolver2), CCpath,["tofResolver"])
                else:
                    _writeParam(str(-tof_resolver1)+","+str(-tof_resolver2), CCpath,["tofResolver"])

                if "/" in tofSource:
                    tofSource = ",".join(tofSource.split("/"))
                _writeParam(tofSource, CCpath,["tofSource"])

            elif useTrignet==4 or useTrignet==5 or useTrignet==6: # Not Use Trignet
                _selectSlit(CCpath,useTrignet,chopperFrequency)

                if "," in t0_offset:
                    offsets = t0_offset.split(",")
                elif  "/" in t0_offset:
                    offsets = t0_offset.split("/")
                else:
                    offsets = [t0_offset]
                try:
                    if len(offsets)==0:
                        tof_offset    = 0
                        tof_resolver1 = 0
                        tof_resolver2 = 0
                    elif len(offsets)==1:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = 0
                        tof_resolver2 = 0
                    elif len(offsets)==2:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = float(offsets[1])
                        tof_resolver2 = 0
                    elif len(offsets)>=3:
                        tof_offset    = float(offsets[0])
                        tof_resolver1 = float(offsets[1])
                        tof_resolver2 = float(offsets[2])
                except:
                    tof_offset    = 0
                    tof_resolver1 = 0
                    tof_resolver2 = 0

                _writeParam(str(tof_offset),CCpath,["tofOffset"])

                if DetType=="uPSD":
                    _writeParam(str(-tof_resolver1)+","+str(-tof_resolver2), CCpath,["tofResolver"])
                else:
                    _writeParam(str(-tof_resolver1)+","+str(-tof_resolver2), CCpath,["tofResolver"])

                if "/" in tofSource:
                    tofSource = ",".join(tofSource.split("/"))
                _writeParam(tofSource, CCpath,["tofSource"])

            self.t0_offset = 0  # AS add [t0_offset] 20140522 for DNA
        else:
            try:
                if "," in t0_offset:
                    self.t0_offset = float(t0_offset.split(",")[0])
                elif  "/" in t0_offset:
                    self.t0_offset = float(t0_offset.split("/")[0])
                else:
                    self.t0_offset = float(t0_offset)
            except:
                self.t0_offset = 0

            self.caseInfoFile     = ""
            ##[inamura 180911]-->
            #self.chopCondInfoFile = ""
            self.chopCondInfoFile = "%f,%f"%(self.lambda_Center,self.lambda_Delta)
            print("### [inamura 180911] chopCondInfoFile="+self.chopCondInfoFile)
            ##<--[inamura 180911]

    def MakeWiringFile(self,WIoutput=None):
        if self.anaEnv== None:
            print(self.CommentHead+"Set file name of environment file (loadEnvFile).")
            return
        
        #path_org_wf = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",self.param_files["WiringInfo"])
        path_org_wf = os.path.join(mu.UtsusemiEnvGetBaseDir(),self.instCode,"ana","xml",self.param_files["WiringInfo"])
        if not os.path.exists(path_org_wf):
            print(self.CommentHead+"ERROR: There is no original wiring file,",path_org_wf)
            return -1
        
        return self._MakeWiringFile(path_org_wf,WIoutput=WIoutput)
            

    def _MakeWiringFile(self,path_org_wf,p=None,WIoutput=None):
        print(self.CommentHead+"Read Original WiringInfo ("+path_org_wf+")")
        ed = ED.EditWiringInfo(path_org_wf)
        daq_list=ed.InstInfo.PutContainerIdList()

        for daq_r in daq_list:
            ed.SuspendDaq(daq_r)
        
        if (self.startDet>=0) and (self.endDet<=ed.MaxDetId):
            for i in range(int(self.startDet),int(self.endDet+1)):
                (dam,daq_i,mod_i) = ed.DetInfoList[i]
                if self.isDebug:
                    print("dam,daq_i,mod_i",dam,daq_i,mod_i)
                for j in ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainerIdList():
                    info = ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainer(j) 
                    info.SetStatus(1)
        elif self.startDet<0 and self.endDet<0:
            for daq_r in daq_list:
                ed.ResumeDaq(daq_r)
        elif self.startDet<0 and self.endDet<=ed.MaxDetId:
            for daq_r in daq_list:
                ed.ResumeDaq(daq_r)
            for i in range( int(self.endDet),int(ed.MaxDetId+1)):
                for j in ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainerIdList():
                    info = ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainer(j) 
                    info.SetStatus(0)
        elif self.startDet>=0 and self.endDet<0:
            for i in range( int(self.startDet),int(ed.MaxDetId+1)):
                for j in ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainerIdList():
                    info = ed.InstInfo.PutContainer(daq_i).PutContainer(mod_i).PutContainer(j) 
                    info.SetStatus(1)
        ed.SelectByDetType( self.DetType )
        
        if self.frameInfo[0]!=0:
            ed.set_FrameInfo( self.frameInfo[0],self.frameInfo[1] )
            if self.isDebug:
                print(self.CommentHead+("Set FrameNo %d Boundary TOF %f" % (self.frameInfo[0],self.frameInfo[1] )))
        
        if self.numOfPixelOnDet!=-1:
            ed.ReSetNumOfPixel( 0,ed.MaxDetId, 0, self.numOfPixelOnDet )
            if self.isDebug:
                print(self.CommentHead+"Change the number of pixels on one PSD to ",self.numOfPixelOnDet)

        if self.ConvType!=-1:
            ptnId = ed.change_TofBinPattern(type=self.ConvType,cont_in=self.Params)
            #ed.setall_TofBinInfo(ptnId,0)
            ed.setall_TofBinInfo(ptnId,self.t0_offset) # AS add [t0_offset] 20140522 for DNA
            print(self.CommentHead+"ConvType=",self.ConvType,", Params = ",self.Params)
        
        self.param_files["WiringInfo"] = "%s_%3s%06d_%06d_%s" % (os.environ["USER"],self.instCode,self.runNo,os.getpid(),self.param_files["WiringInfo"])

        #if "UTSUSEMI_USR_PRIV_HOME" in os.environ:
        if WIoutput is None:
            udir = mu.UtsusemiEnvGetUserDir()
            if udir!="":
                ss = os.path.join(udir,"ana","xml",self.param_files["WiringInfo"])
            else:
                #ss = os.path.join(os.environ["HOME"],"ana","xml",self.param_files["WiringInfo"])
                ss = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","xml",self.param_files["WiringInfo"])
        else:
            ss = WIoutput
        ed.SaveToXml( ss )
        comm = "chmod go+w "+ss
        print(self.CommentHead+"Do command = ",comm)
        try:
            os.system(comm)
        except:
            print(self.CommentHead+" Command missed.")
        #------------------------------------------------------------------------------------------------------------

        import sys
        ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
        if ver<2.5:
            from elementtree.ElementTree import ElementTree,SubElement
        else:
            from xml.etree.ElementTree import ElementTree,SubElement

        def _writeParam(dpath,items1,items2):
            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()

                ele=ele.find("pixelInfo")
                num=len(ele.findall("daq"))

                sele=SubElement(ele,"daq")
                ele.set("n",str(num+1))
                for item in items1:
                    if item[0]=="i":
                        sele.set(item[0],str(num))
                    else:
                        sele.set(item[0],item[1])

                sele2=SubElement(sele,"module")
                for item in items2:
                    sele2.set(item[0],item[1])

                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):
            if dpath!="":
                fd = open(dpath,'rb')
                dom=ElementTree(file=fd)
                fd.close()

                ele = dom.getroot()
                for param,j in params:
                    if j!=0:
                        ele = ele.findall(param)[j]
                    else:
                        ele = ele.find(param)
                    if ele==None:
                        print("input param is not found",param)
                        return ""

                return ele.items()

        def _copyParamTrignt():
            items1 = _readParam(path_org_wf,[("pixelInfo",0),("daq",3)])
            items2 = _readParam(path_org_wf,[("pixelInfo",0),("daq",3),("module",0)])
            _writeParam(ss,items1,items2)
        try:
            _copyParamTrignt()
        except:
            print("_copyParamTrignt Error")
    def GetHistogram(self,daq=-1):
        if self.anaEnv==None:
            print(self.CommentHead+" There is no information.")
            return -1

        #20151202 start
        fname  = self.param_files["DetectorInfo"][:-4]
        footer = self.param_files["DetectorInfo"][-4:]
        pid = str(os.getpid())
        #20151202 end
        DAT = EtoE.GetHistogram(eventtype=self.DetType,
                                runnumber=self.runNo,
                                WiringInfo_xml=self.param_files["WiringInfo"],
                                DetectorInfo_xml=fname+"_"+pid+footer,
                                CaseInfo_xml=self.caseInfoFile,
                                ChopCondInfo_xml=self.chopCondInfoFile,
                                TOFOffsetFile=self.TOFOffsetFile,
                                useTrignet=self.useTrignet,
                                starttime=self.SliceEventStart,
                                endtime=self.SliceEventEnd,
                                isPH=self.isPulseHeight,
                                isHistogram=self.isHistogram )#[inamura 170616]
        """
        DAT = EtoE.GetHistogram( self.DetType, self.runNo,
                                 p.Info["wiringfile"],
                                 self.anaEnv.Info["PositioningFile"],
                                 self.SliceEventStart,self.SliceEventEnd )
        """
        """
        if not self.isDebug:
            comm = "rm -rf %s" % (os.path.join(os.environ["HOME"],"ana","xml",self.param_files["WiringInfo"]))
            try:
                os.system(comm)
            except:
                print self.CommentHead+" False to delete %s."%(os.path.join(os.environ["HOME"],"ana","xml",self.param_files["WiringInfo"]))
        """
        return DAT


###############################################
### Sample for utilization of Histogram class
###############################################
def GetHistDTconst(runNo=-1,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,pixelNo=-1,bTOF=0.0,detType="PSD"):
    """
    Load EventData and convert to histogram.
    GetHistogram(runNo=-1,paraFlag=0,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,pixelNo=-1,bTOF=0.0)
    @param runNo    (int) Run Number
    @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 pixelNo  (int) the number of pixels on one PSD
    @param bTOF     (double) boundary tof for double frame mode
    @param detType  (string) PSD or N2MON
    @retval ElementContainerMatrix
    """
    fInfo = [0,0.0]
    if bTOF!=0.0:
        fInfo[0] = int( bTOF/40000.0 )
        fInfo[1] = bTOF - float(fInfo[0])*40000.0

    params = [startTOF, endTOF, binTOF ]
    drange = [startPSD, endPSD]
    trange = [-1.0, -1.0]
    h=Historam(runNo=runNo,
               ConvType=2,
               Params=params,
               DetRange=drange,
               pixelNo=pixelNo,
               TimeRange=trange,
               frameInfo=fInfo,
               DetType=detType,
               )
    
    if h.Status==0:
        h.MakeWiringFile()
        return h.GetHistogram()

def GetHistogramSimple( runNo=-1,wiringFile="WiringFile_org.xml",detectCompFile="DetectorPosi2.xml", startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,pixelNo=-1,bTOF=0.0 ):
    """
    Load EventData and confert to histogram using given WiringFile and DetectorCompFile.
    GetHistogramSimple( runNo=-1,wiringFile="WiringFile_org.xml",detectCompFile="DetectorPosi2.xml", 
                        startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,pixelNo=-1,bTOF=0.0
                      )
    @param runNo    (int) Run Number
    @param wiringFile (string) Wiring File name
    @param detectCompFile (string) Detector Components file name
    @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 pixelNo  (int) the number of pixels on one PSD
    @param bTOF (double) boundary tof for double frame mode
    @retval ElementContainerMatrix
    """
    in_envFile = wiringFile+","+detectCompFile
    in_envFile = in_envFile.replace(" ","")

    fInfo = [0,0.0]

    if bTOF!=0.0:
        fInfo[0] = int( bTOF/40000.0 )
        fInfo[1] = bTOF - float(fInfo[0])*40000.0

    params = [startTOF, endTOF, binTOF ]
    drange = [startPSD, endPSD]
    trange = [-1.0, -1.0]
    h=Histogram(runNo=runNo,
                ConvType=-1,
                Params=params,
                DetRange=drange,
                pixelNo=pixelNo,
                TimeRange=trange,
                envFile=in_envFile,
                frameInfo=fInfo,
                DetType="PSD",
                isPulseHeight=False,
                isDebug=False
                )
    
    if h.Status==0:
        h.MakeWiringFile()
        return h.GetHistogram()

def GetHistogramByTime(runNo=-1,startTOF=-1,endTOF=-1,binTOF=-1,startPSD=-1,endPSD=-1,pixelNo=-1,startTime=-1.0,endTime=-1.0,bTOF=0.0):
    """
    Load EventData and convert to histogram.
    Histogram(runNo,paraFlag,startTOF=-1,endTOF=-1,binTOF=-1,pixelNo=-1,startPSD=-1,endPSD=-1,envFile)
    @param runNo    (int) Run Number
    @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 pixelNo  (int) the number of pixels on one PSD
    @param startTime (float)
    @param endTime   (float)
    @param bTOF (double) boundary tof for double frame mode
    @retval ElementContainerMatrix
    """
    fInfo = [0,0.0]
    if bTOF!=0.0:
        fInfo[0] = int( bTOF/40000.0 )
        fInfo[1] = bTOF - float(fInfo[0])*40000.0

    params = [startTOF, endTOF, binTOF ]
    drange = [startPSD, endPSD]
    trange = [startTime, endTime]
    h=Histogram(runNo=runNo,
                ConvType=2,
                Params=params,
                DetRange=drange,
                pixelNo=pixelNo,
                TimeRange=trange,
                frameInfo=fInfo,
                DetType="PSD",
                isPulseHeight=False,
                isDebug=False
                )
    
    if h.Status==0:
        h.MakeWiringFile()
        return h.GetHistogram()
    
def GetHistogramOfConv( runNo=-1,
                        ConvType=-1,
                        Params=[],
                        detectorRange=[-1,-1],
                        numOfPixel=-1,
                        timeRange=[-1.0,-1.0],
                        frameInfo=[0,0.0],
                        DetType="PSD",
                        useTrignet=0,
                        t0_offset="0.0", # AS add [t0_offset] 20140522 for DNA
                        tofOffsetFile = "",
                        tofSource="0.0,400.0",
                        ChopperFrequency=225.0,
                        isHistogram=True,
                        WIoutput = None
                        ):
                        
    """
    Load EventData and convert to histogram
    GetHistogramOfConv( runNo=-1,
                        ConvType=-1,
                        Params=[],
                        detectorRange=[-1,-1],
                        numOfPixel=-1,
                        timeRange=[-1.0,-1.0],
                        frameInfo=[0,0.0],
                        DetType="PSD"
                        )
    @param runNo         (int)   run number
    @param ConvType      (int)   Conversion Type 
    @param Params        (list)  parameters required by ConvType
    @param detectorRange (list)  range of detectors [startId, endId]
    @param numOfPixel    (int)   the number of pixels of a PSD
    @param timeRange     (list)  time range [start Time[sec], end Time[sec] ]
    @param frameInfo     (list)  frame info
    @param DetType       (string) "PSD" or "N2MON"
    @retval ElementContainerMatrix
    """
    h=Histogram(runNo=runNo,
                ConvType=ConvType,
                Params=Params,
                DetRange=detectorRange,
                pixelNo=numOfPixel,
                TimeRange=timeRange,
                frameInfo=frameInfo,
                DetType=DetType,
                useTrignet=useTrignet,
                isPulseHeight=False,
                isDebug=False,
                t0_offset=t0_offset,# AS add [t0_offset] 20140522 for DNA
                tofOffsetFile=tofOffsetFile,
                tofSource=tofSource,
                chopperFrequency=ChopperFrequency,
                isHistogram=isHistogram #[inamura 170616]
                )

    if h.Status==0:
        if WIoutput is not None:
            h.MakeWiringFile(WIoutput=WIoutput)
            return None
        h.MakeWiringFile()
        return h.GetHistogram()

def GetPulseHeight(runNo=-1,
                   detType="PSD",
                   phHist=[0,10000,10],
                   detectorRange=[-1,-1],
                   timeRange=[-1.0,-1.0]
                   ):
    
    """
    Load EventData and make PulseHeight hist
    GetPulseHeight(runNo=-1,
                   detType="PSD",
                   phHist=[0,10000,10],
                   detectorRange=[-1,-1],
                   timeRange=[-1.0,-1.0]
                   )
    @param runNo
    @param detType
    @param phHist
    @param detectorRange
    @param timeRange
    @retval ElementContainerMatrix
    """
    h=Histogram(runNo=runNo,
                ConvType=2,
                Params=phHist,
                DetRange=detectorRange,
                pixelNo=1,
                TimeRange=timeRange,
                DetType=detType,
                isPulseHeight=True,
                isDebug=False
                )
    
    if h.Status==0:
        h.MakeWiringFile()
        return h.GetHistogram()

def GetAnalysisParameter(laticeSpace):

    Params=[0.0   , 1.0,    0.1,      0.0,      0.0,     0.0,       laticeSpace, 0.0]
    #      [Hw_min, Hw_max, Hw_width, Lambda_c, dLambda, t0_offset, LaticeSpace, L1]
    """
    h=Histogram(runNo=-1,
                ConvType=27,
                Params=Params,
                DetRange=[-1,-1],
                DetType="uPSD"
                )

    if h.Status==0:
        h.MakeWiringFile()

    WiringInfo_xml   = h.anaEnv.Info["SingleMode"].Info["wiringfile"]
    DetectorInfo_xml = h.anaEnv.Info["PositioningFile"]

    if os.environ.has_key("UTSUSEMI_USR_PRIV_HOME"):
        WIpath=os.path.join(os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",WiringInfo_xml)
    else:
        WIpath=os.path.join(os.environ["HOME"],"ana","xml",WiringInfo_xml)
    """

    #[inamura 180907]-->
    ana_env = mu.UtsusemiAnaEnvironReader("environ_ana.xml")
    param_files = ana_env.PutParamFiles(1)
    #wfile = os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",param_files[0])
    wfile = os.path.join(mu.UtsusemiEnvGetBaseDir(),mu.UtsusemiEnvGetInstCode(),"ana","xml",param_files[0])
    ed = ED.EditWiringInfo(wfile)
    ed.SelectByDetType( "uPSD" )
    wfile_tmp = "%s_DNA000000_%06d_%s" % (os.environ["USER"],os.getpid(),param_files[0])
    #WIpath = os.path.join( os.environ["UTSUSEMI_USR_PRIV_HOME"],"ana","xml",wfile_tmp )
    WIpath = os.path.join( mu.UtsusemiEnvGetUserDir(),"ana","xml",wfile_tmp )
    ed.SaveToXml(WIpath)
    DetectorInfo_xml = param_files[1]
    #<--[inamura 180907]
    #DCpath=os.path.join(os.environ["UTSUSEMI_USR_DIR"],"ana","xml",DetectorInfo_xml)
    DCpath=os.path.join(mu.UtsusemiEnvGetBaseDir(),mu.UtsusemiEnvGetInstCode(),"ana","xml",DetectorInfo_xml)

    import Manyo.DNA as md

    evt = md.UtsusemiEventDataConverterDNA()
    evt.LoadParamFiles( WIpath, DCpath )
    evt.SetHistAllocation()

    ef = evt.PutEf()
    pa = evt.PutPolarAngle()
    aa = evt.PutAzimuthAngle()

    ed = ED.EditWiringInfo(WIpath)
    sum_of_det,sum_of_pixel=ed.PutNumOfBoth()

    efArray=[]
    aaArray=[]
    paArray=[]
    i=0
    for detId in range(sum_of_det):
        (flag,daq,mod) = ed.DetInfoList[detId]
        info = ed.InstInfo.PutContainer(daq).PutContainer(mod).PutContainer(detId)
        did, numOfPixel, numAxis= info.PutPixelInfo()
        efTmp=[]
        aaTmp=[]
        paTmp=[]
        for j in range(numOfPixel):
            efTmp.append(ef[i])
            aaTmp.append(aa[i])
            paTmp.append(pa[i])
            i+=1
        efArray.append(efTmp)
        aaArray.append(aaTmp)
        paArray.append(paTmp)

    del evt

    #[inamura 180907]-->
    #import cPickle as pickle
    #fo = open("/home/dnaadmin/YI_180907_new_ef.dmp","w")
    #pickle.dump( efArray, fo )
    #fo.close()
    #fo = open("/home/dnaadmin/YI_180907_new_aa.dmp","w")
    #pickle.dump( aaArray, fo )
    #fo.close()
    #fo = open("/home/dnaadmin/YI_180907_new_pa.dmp","w")
    #pickle.dump( paArray, fo )
    #fo.close()
    ##sys.exit(0)
    #<--[inamura 180907]

    return efArray,aaArray,paArray

