import utsusemi.DNA.ana.Reduction.Histogram as HH
import Manyo.DNA as md
import Manyo as mm
import numpy
import scipy
import scipy.stats
import math
import os
import multiprocessing
import time
#-------------------------------------------------------------------------------------------------
def GetAnalysisParameter(laticeSpace=3.134600):
    # LaticeSpace dependence
    params=[0.0   ,    1.0,      0.1, 0.0, 0.0, 0.0, laticeSpace, 0.000000]

    return HH.GetAnalysisParameter(laticeSpace)
#-------------------------------------------------------------------------------------------------
def CheckFitFuncDegree(eiArray,degree):

    if len(eiArray)>degree:
        return True
    else:
        print "This function requires the following conditions."
        print " ( initial Energy Array Length > degree )"
        return False
#-------------------------------------------------------------------------------------------------
def CalcASS(eiArray, sampleFileName ,degree, output, laticeSpace=3.134600, alpha=1.0):

    if os.path.exists(output):
        os.remove(output)

    ef,aa,pa=GetAnalysisParameter(laticeSpace)

    #psdn   = 224
    psdn   = len(ef)
    #psdn   = 1

    pixeld = 60

    pixeln=len(ef[0])/pixeld
    #pixeln = 6
    #pixeln = 1

    if CheckFitFuncDegree(eiArray,degree):
        print "\n0/"+str(psdn*pixeln*pixeld)+"\n"
        ptime=time.time()
        for i in range(psdn):
            for j in range(pixeln):
                psd   = [i]
                pixel = range(j*pixeld,(j+1)*pixeld)
                #CalcACoeffArray(psd, pixel, eiArray, sampleFileName ,degree, output, "ASS", ef, pa, aa, alpha)
                CalcACoeffArrayMulth(psd, pixel, eiArray, sampleFileName ,degree, output, "ASS", ef, pa, aa, alpha)
                print "\n" + str((j+1) * pixeld + i * pixeln * pixeld)+"/" + str(psdn * pixeln * pixeld) + "\n"
                ntime=time.time()
                print ntime-ptime
                ptime=ntime
#-------------------------------------------------------------------------------------------------
def CalcACSC(eiArray, sampleFileName ,degree, output, laticeSpace=3.134600, alpha=1.0):
    if os.path.exists(output):
        os.remove(output)

    ef,aa,pa=GetAnalysisParameter(laticeSpace)

    #psdn   = 224
    psdn    = len(ef)
    #psdn   = 1
    pixeld  = 60
    pixeln  = len(ef[0])/pixeld
    #pixeln = 6
    #pixeln = 1

    if CheckFitFuncDegree(eiArray,degree):
        print "\n0/"+str(psdn*pixeln*pixeld)+"\n"
        ptime=time.time()
        for i in range(psdn):
            for j in range(pixeln):
                psd   = [i]
                pixel = range(j*pixeld,(j+1)*pixeld)
                #CalcACoeffArray(psd, pixel, eiArray, sampleFileName ,degree, output, "ACSC", ef, pa, aa, alpha)
                CalcACoeffArrayMulth(psd, pixel, eiArray, sampleFileName ,degree, output, "ACSC", ef, pa, aa, alpha)
                print "\n" + str((j+1) * pixeld + i * pixeln * pixeld)+"/" + str(psdn * pixeln * pixeld) + "\n"
                ntime=time.time()
                print ntime-ptime
                ptime=ntime
#-------------------------------------------------------------------------------------------------
def CalcACSS(eiArray, sampleFileName ,degree, output, laticeSpace=3.134600, alpha=1.0):
    if os.path.exists(output):
        os.remove(output)

    ef,aa,pa=GetAnalysisParameter(laticeSpace)

    #psdn   = 224
    psdn    = len(ef)
    #psdn   = 1
    pixeld  = 60
    pixeln  = len(ef[0])/pixeld
    #pixeln = 6
    #pixeln = 1

    if CheckFitFuncDegree(eiArray,degree):
        print "\n0/"+str(psdn*pixeln*pixeld)+"\n"
        ptime=time.time()
        for i in range(psdn):
            for j in range(pixeln):
                psd   = [i]
                pixel = range(j*pixeld,(j+1)*pixeld)
                #CalcACoeffArray(psd, pixel, eiArray, sampleFileName ,degree, output, "ACSS", ef, pa, aa, alpha)
                CalcACoeffArrayMulth(psd, pixel, eiArray, sampleFileName ,degree, output, "ACSS", ef, pa, aa, alpha)
                print "\n" + str((j+1) * pixeld + i * pixeln * pixeld)+"/" + str(psdn * pixeln * pixeld) + "\n"
                ntime=time.time()
                print ntime-ptime
                ptime=ntime
#-------------------------------------------------------------------------------------------------
def CalcACC(eiArray, sampleFileName ,degree, output, laticeSpace=3.134600, alpha=1.0):
    if os.path.exists(output):
        os.remove(output)

    ef,aa,pa=GetAnalysisParameter(laticeSpace)

    #psdn   = 224
    psdn    = len(ef)
    #psdn   = 1
    pixeld  = 60
    pixeln  = len(ef[0])/pixeld
    #pixeln = 6
    #pixeln = 1

    if CheckFitFuncDegree(eiArray,degree):
        print "\n0/"+str(psdn*pixeln*pixeld)+"\n"
        ptime=time.time()
        for i in range(psdn):
            for j in range(pixeln):
                psd   = [i]
                pixel = range(j*pixeld,(j+1)*pixeld)
                #CalcACoeffArray(psd, pixel, eiArray, sampleFileName ,degree, output, "ACC", ef, pa, aa, alpha)
                CalcACoeffArrayMulth(psd, pixel, eiArray, sampleFileName ,degree, output, "ACC", ef, pa, aa, alpha)
                print "\n" + str((j+1) * pixeld + i * pixeln * pixeld)+"/" + str(psdn * pixeln * pixeld) + "\n"
                ntime=time.time()
                print ntime-ptime
                ptime=ntime
#-------------------------------------------------------------------------------------------------
def CalcASSOfElastic(sampleFileName, output, laticeSpace=3.134600, alpha=1.0):
    if os.path.exists(output):
        os.remove(output)

    ef,aa,pa=GetAnalysisParameter(laticeSpace)
    psdn   = len(ef)
    #psdn    = 1
    pixeln = len(ef[0])

    for i in range(psdn):
    #for i in range(55,60):
        psd = [i]
        pixel = range(pixeln)
        CalcACoeffOfElasticArrayMulth(psd, pixel, sampleFileName, output, "ASS", ef, pa, aa)
        print "\n" + str( (i+1) * pixeln)+"/" + str(pixeln * psdn) + "\n"
#-------------------------------------------------------------------------------------------------
def CalcACoeffArray(psd, pixel, eiArray, sampleFileName ,degree, output, Atype, ef, pa, aa, alpha):
    retY = PutACoeffArray(psd, pixel, eiArray, sampleFileName, Atype, ef, pa, aa, alpha)
    retP = ExecPolyFit(eiArray, retY, degree)
    WriteAbsorptionCoefficientFile(output,psd,pixel,retP,"a")
#-------------------------------------------------------------------------------------------------
def CalcACoeffArrayMulth(psd, pixel, eiArray, sampleFileName ,degree, output, Atype, ef, pa, aa, alpha):

    def func(pix,queue):
        retY = PutACoeffArray(psd, pix, eiArray, sampleFileName, Atype, ef, pa, aa, alpha)
        queue.put(retY)

    MULTH=12
    pixs=[]
    div=int(math.ceil(float(len(pixel))/MULTH))
    for i in range(MULTH-1):
        pixs.append( pixel[div*(i):div*(i+1)])
    pixs.append( pixel[div*(i+1):])

    q = [multiprocessing.Queue() for i in range(MULTH)]
    p = [multiprocessing.Process(target=func, args=(pixs[i],q[i])) for i in range(MULTH)]

    for i in range(MULTH):p[i].start()

    for i in range(MULTH):p[i].join()

    retY=[]
    for i in range(MULTH):
        retY += q[i].get()[0]
    retY = [retY]

    retP = ExecPolyFit(eiArray, retY, degree)
    WriteAbsorptionCoefficientFile(output,psd,pixel,retP,"a")
#-------------------------------------------------------------------------------------------------
def CalcACoeffOfElasticArray(psd, pixel, sampleFileName, output, Atype, ef, pa, aa):
    retY = PutACoeffOfElasticArray(psd, pixel, sampleFileName, "ASS", ef, pa, aa)
    WriteAbsorptionCoefficientFileOfElastic(output,retY,"a")
#-------------------------------------------------------------------------------------------------
def CalcACoeffOfElasticArrayMulth(psd, pixel, sampleFileName, output, Atype, ef, pa, aa):
    def func(pix,queue):
        retY = PutACoeffOfElasticArray(psd, pix, sampleFileName, Atype, ef, pa, aa)
        queue.put(retY)

    MULTH=12
    pixs=[]
    div=int(math.ceil(float(len(pixel))/MULTH))
    for i in range(MULTH-1):
        pixs.append( pixel[div*(i):div*(i+1)])
    pixs.append( pixel[div*(i+1):])

    q = [multiprocessing.Queue() for i in range(MULTH)]
    p = [multiprocessing.Process(target=func, args=(pixs[i],q[i])) for i in range(MULTH)]

    for i in range(MULTH):p[i].start()

    for i in range(MULTH):p[i].join()

    retY=[]
    for i in range(MULTH):
        retY += q[i].get()[0]

    WriteAbsorptionCoefficientFileOfElastic(output,retY,"a")
#-------------------------------------------------------------------------------------------------
def PutACoeffArray(psd, pixel, eiArray, sampleFileName, Atype, ef, pa, aa, alpha=1):

    flagPsd   = isinstance(psd,(list,tuple))
    flagPixel = isinstance(pixel,(list,tuple))

    t = md.AdvCorrectionAbsorptionDNA(sampleFileName)
    RADIAN2DEGREE = 180.0/numpy.pi

    t.SetSigmaCoefficient(1.0, 1.0, alpha)

    if Atype=="ASS":
        GetA=t.GetASS
    elif Atype=="ACSC":
        GetA=t.GetACSC
    elif Atype=="ACSS":
        GetA=t.GetACSS
    elif Atype=="ACC":
        GetA=t.GetACC
    else:
        return [[]]

    if not flagPsd:
        psd=[psd]
    if not flagPixel:
        pixel=[pixel]
    ret =[]
    for ps in psd:
        retTmp=[]
        for pi in pixel:
            polarAngle   = pa[ps][pi]*RADIAN2DEGREE
            azimuthAngle = aa[ps][pi]*RADIAN2DEGREE
            energyFinal  = ef[ps][pi]
            retY = numpy.array([GetA(polarAngle, azimuthAngle, ei, energyFinal) for ei in eiArray])

            retTmp.append(retY)
        ret.append(retTmp)

    del t
    return ret
#-------------------------------------------------------------------------------------------------
def PutACoeffOfElasticArray(psd, pixel, sampleFileName, Atype, ef, pa, aa):

    flagPsd   = isinstance(psd,(list,tuple))
    flagPixel = isinstance(pixel,(list,tuple))

    t = md.AdvCorrectionAbsorptionDNA(sampleFileName)
    RADIAN2DEGREE = 180.0/numpy.pi
    if Atype=="ASS":
        GetA=t.GetASS
    elif Atype=="ACSC":
        GetA=t.GetACSC
    elif Atype=="ACSS":
        GetA=t.GetACSS
    elif Atype=="ACC":
        GetA=t.GetACC
    else:
        return [[]]

    if not flagPsd:
        psd=[psd]
    if not flagPixel:
        pixel=[pixel]
    ret =[]
    for ps in psd:
        retTmp=[]
        for pi in pixel:
            polarAngle   = pa[ps][pi]*RADIAN2DEGREE
            azimuthAngle = aa[ps][pi]*RADIAN2DEGREE
            energyFinal  = ef[ps][pi]
            retY = GetA(polarAngle, azimuthAngle, energyFinal, energyFinal)
            retTmp.append(retY)
        ret.append(retTmp)

    del t
    return ret

#-------------------------------------------------------------------------------------------------
def ExecPolyFit(xarray,yarray,degree):
    if  isinstance(yarray[0],(list,tuple,numpy.ndarray)):
        ret = [ExecPolyFit(xarray,ys,degree) for ys in yarray]
        return ret
    else:
        ret = FitPolyFunc(xarray,yarray,degree)
        return ret
#-------------------------------------------------------------------------------------------------
def FitPolyFunc(xarray,yarray,degree):

    if degree>0:
        popt = numpy.polyfit(xarray,yarray,degree)
        #if len(popt)=4, y = popt[0]*x^3 + popt[1]*x^2 + popt[2]*x +popt[3]
        yexp = numpy.poly1d(popt)(xarray)
        chisq,p=scipy.stats.chisquare(yarray,yexp)
    else:
        popt=[]
        chisq=0
    return popt
#-------------------------------------------------------------------------------------------------
def WriteAbsorptionCoefficientFile(filename,psd,pixel,param,mode):
    # mode="w", write
    # mode="a", append
    sep = ","

    flagPsd   = isinstance(psd,(list,tuple))
    flagPixel = isinstance(pixel,(list,tuple))
    if not flagPsd:
        psd=[psd]
    if not flagPixel:
        pixel=[pixel]

    f=open(filename,mode)
    for i in range(len(psd)):
        for j in range(len(pixel)):
            text="%d,%d,"%(psd[i],pixel[j])+sep.join(["%.4e"%val for val in param[i][j]])+"\n"
            f.write(text)

    f.close()
#-------------------------------------------------------------------------------------------------
def ReadAbsorptionCoefficientFile(filename):
    f=open(filename)
    sep=","

    d=dict()
    for line in f:
        ll = line.split(sep)

        psd   = int(ll[0])
        if not d.has_key(psd):
            d[psd]=dict()

        pixel = int(ll[1])
        param = [float(p) for p in ll[2:]]
        d[psd][pixel]=param

    return d
#-------------------------------------------------------------------------------------------------
def ExecAbsorptionCorrection(ECM,ds,modes):

    ecaSize = ECM.PutTableSize()
    ecm = mm.ElementContainerMatrix(ECM.PutHeader())
    for i in range(ecaSize):
        if i%22==1:
            print str(int(i/22*10)) +" %"

        ECA = ECM.Put(i)
        eca = mm.ElementContainerArray(ECA.PutHeader())
        ecSize = ECA.PutTableSize()
        for j in range(ecSize):

            EC = ECA.Put(j)
            ec=mm.ElementContainer(EC.PutHeader())

            ecXn = numpy.array(EC.PutXList())
            ecX  = (ecXn[1:]+ecXn[:-1])*0.5
            ecY  = numpy.array(EC.PutYList())

            if _checkListDepth(ds)==3:   # apply single absp. coefficient
                abcn = PutAbsorptionCoefficient(ecX,ds,i,j)
                # if modes==0:
                if modes==1:             # corrected by M. Matsuura 2015.3.3 
                    ecYnew = ecY*abcn    # numpy.array * numpy.array
                else:
                    ecYnew = ecY/abcn    # numpy.array / numpy.array
            elif _checkListDepth(ds)==4: # apply some absp. coefficients
                abcns = [PutAbsorptionCoefficient(ecX,d,i,j) for d in ds]
                for abcn, mode in zip(abcns,modes):
                    if mode==0:
                        ecY = ecY*abcn   # numpy.array * numpy.array
                    else:
                        ecY = ecY/abcn   # numpy.array / numpy.array
                    ecYnew = ecY

            ecXnew = ecXn
            ecEnew = numpy.array(EC.PutEList())
            xkey,ykey,ekey    = [EC.PutXKey(),EC.PutYKey(),EC.PutEKey()]
            xunit,yunit,eunit = [EC.PutUnit(key) for key in [xkey,ykey,ekey]]

            ec.Add(xkey,ecXnew.tolist())
            ec.Add(ykey,ecYnew.tolist())
            ec.Add(ekey,ecEnew.tolist())
            ec.SetKeys(xkey,ykey,ekey)
            ec.SetUnit(xkey,xunit)
            ec.SetUnit(ykey,yunit)
            ec.SetUnit(ekey,eunit)

            errMaskArray   = ecEnew>=0
            ecYVal         = ecYnew[errMaskArray]
            sumVal         = numpy.sum(ecYVal)
            ech=ec.PutHeaderPointer()
            ech.OverWrite("TotalCounts",sumVal)

            eca.Add(ec)
        ecm.Add(eca)
    return ecm
#-------------------------------------------------------------------------------------------------
def SubstractionEmptyCellData(DAT1,DAT2):
    ecaSize = DAT1.PutTableSize()
    ecm = mm.ElementContainerMatrix(DAT1.PutHeader())
    for i in range(ecaSize):
        if i%22==1:
            print str(int(i/22*10)) +" %"

        ECA1 = DAT1.Put(i)
        ECA2 = DAT2.Put(i)
        eca = mm.ElementContainerArray(ECA1.PutHeader())
        ecSize = ECA1.PutTableSize()
        for j in range(ecSize):
            EC1 = ECA1.Put(j)
            EC2 = ECA2.Put(j)
            ec=mm.ElementContainer(EC1.PutHeader())

            ecX = numpy.array(EC1.PutXList())

            ecY1 = numpy.array(EC1.PutYList())
            ecE1 = numpy.array(EC1.PutEList())

            ecY2 = numpy.array(EC2.PutYList())
            ecE2 = numpy.array(EC2.PutEList())

            ecI1 = ecE1 != -1
            ecI2 = ecE2 != -1
            ecI  = numpy.logical_and(ecI1,ecI2)

            ecXnew = ecX
            ecYnew = (ecY1 - ecY2)*ecI
            ecEnew = numpy.sqrt(ecY1*ecY1 + ecY2*ecY2)*ecI

            xkey,ykey,ekey    = [EC1.PutXKey(),EC1.PutYKey(),EC1.PutEKey()]
            xunit,yunit,eunit = [EC1.PutUnit(key) for key in [xkey,ykey,ekey]]
            ec.Add(xkey,ecXnew.tolist())
            ec.Add(ykey,ecYnew.tolist())
            ec.Add(ekey,ecEnew.tolist())
            ec.SetKeys(xkey,ykey,ekey)
            ec.SetUnit(xkey,xunit)
            ec.SetUnit(ykey,yunit)
            ec.SetUnit(ekey,eunit)

            errMaskArray   = ecEnew>=0
            ecYVal         = ecYnew[errMaskArray]
            sumVal         = numpy.sum(ecYVal)

            ech=ec.PutHeaderPointer()
            ech.OverWrite("TotalCounts",sumVal)
            eca.Add(ec)
        ecm.Add(eca)

    return ecm
#-------------------------------------------------------------------------------------------------
def DoAbsorptionCorrection(DAT,filename,mode=1):

    filenameFlag = isinstance(filename, (list,tuple))
    if filenameFlag:
        d = [ReadAbsorptionCoefficientFile(name) for name in filename]
    else:
        d = ReadAbsorptionCoefficientFile(filename)

    ECM = ExecAbsorptionCorrection(DAT,d,mode)
    return ECM
#-------------------------------------------------------------------------------------------------
def DoAbsorptionCorrectionWithoutCellData(ECM,filename):
    print "exec Absorption Correction"
    #print "exec *A           : Start"
    print "exec /A           : Start" # Corrected by M. Matsuura 2015.3.3
    ECM_I_S = DoAbsorptionCorrection(ECM, [filename], [0])
    #print "exec *A           : End"
    print "exec /A           : End" # Corrected by M. Matsuura 2015.3.3    
    return ECM_I_S
#-------------------------------------------------------------------------------------------------
def DoAbsorptionCorrectionWithCellData(ECM_I_SC_SC,ECM_I_C_C,AcscFname,AccFname,AsscFname):
    print "exec Absorption Correction"
    print "exec *Acsc / Acc  : Start"
    ECM_I_C_SC  = DoAbsorptionCorrection(ECM_I_C_C,  [AcscFname,AccFname], [1,0])
    print "exec *Acsc / Acc  : End"
    print "exec Iscsc - Icsc : Start"
    ECM_I_S_SC  = SubstractionEmptyCellData(ECM_I_SC_SC, ECM_I_C_SC)
    print "exec Iscsc - Icsc : End"
    # print "exec *Assc        : Start"
    print "exec /Assc        : Start" # Corrected by M. Matsuura 2015.3.3
    ECM_I_S     = DoAbsorptionCorrection(ECM_I_S_SC, [AsscFname], [0])
    # print "exec *Assc        : End"
    print "exec /Assc        : End"  # Corrected by M. Matsuura 2015.3.3
    return ECM_I_S
#-------------------------------------------------------------------------------------------------
def WriteAbsorptionCoefficientFileOfElastic(filename,param,mode):
    sep = ","
    f=open(filename,mode)

    text = sep.join(["%.4e"%val for val in param])+"\n"
    f.write(text)
    f.close()
#-------------------------------------------------------------------------------------------------
def ReadAbsorptionCoefficientFileOfElastic(filename):
    f=open(filename)
    sep=","

    v=[]
    for line in f:
        ll = line.split(sep)
        p=[float(val) for val in ll]

        v.append(p)
    return v
#-------------------------------------------------------------------------------------------------
def ExecAbsorptionCorrectionOfElastic(ECM,d,mode=0):
    ecaSize = ECM.PutTableSize()
    ecm = mm.ElementContainerMatrix(ECM.PutHeader())

    for i in range(ecaSize):
        if i%22==1:
            print str(int(i/22*10)) +" %"

        ECA = ECM.Put(i)
        eca = mm.ElementContainerArray(ECA.PutHeader())
        ecSize = ECA.PutTableSize()
        for j in range(ecSize):
            EC = ECA.Put(j)
            if mode==1:
                ec = EC.Mul(d[i][j])
            else:
                r=d[i][j]
                if r!=0:
                    ec = EC.Mul(1.0/d[i][j])
                else:
                    ec = EC.Mul(0.0)
            ech    = ec.PutHeaderPointer()

            ecY    = numpy.array(ec.PutYList())
            ecE    = numpy.array(ec.PutEList())
            errMaskArray = ecE>=0
            ecY          = ecY[errMaskArray]
            sumVal = numpy.sum(ecY)

            ech.OverWrite("TotalCounts",sumVal)

            eca.Add(ec)
        ecm.Add(eca)
    return ecm
#-------------------------------------------------------------------------------------------------
def DoAbsorptionCorrectionOfElastic(DAT,filename):
    print "exec Absorption Correction"
    # print "exec *A(E=E_ela)  : Start"
    print "exec /A(E=E_ela)  : Start" # Corrected by M. Matsuura 2015.3.3
    d   = ReadAbsorptionCoefficientFileOfElastic(filename)
    ECM = ExecAbsorptionCorrectionOfElastic(DAT,d)
    # print "exec *A(E=E_ela)  : End"
    print "exec /A(E=E_ela)  : End"  # Corrected by M. Matsuura 2015.3.3
    return ECM
#-------------------------------------------------------------------------------------------------
def PutAbsorptionCoefficient(xarray,paramDict,psd,pixel):
    if paramDict.has_key(psd):
        if paramDict[psd].has_key(pixel):
            return PolyFunction(xarray,paramDict[psd][pixel])
    print "PSD:%d,PIXEL:%d data is not found"%(psd,pixel)
    return numpy.ones(len(xarray))
#-------------------------------------------------------------------------------------------------
def PolyFunction(xarray,param):
    return numpy.poly1d(param)(xarray)
#-------------------------------------------------------------------------------------------------
def CalcAbsorptionCoeff(mode,eiArray, ef, aa, pa, sampleFileName):
    t  = md.AdvCorrectionAbsorptionDNA(sampleFileName)
    if mode=="ACC":
        av = [ t.GetACC(pa,aa,ei,ef) for ei in eiArray ]
    elif mode=="ACSS":
        av = [ t.GetACSS(pa,aa,ei,ef) for ei in eiArray ]
    elif mode=="ACSC":
        av = [ t.GetACSC(pa,aa,ei,ef) for ei in eiArray ]
    else:
        av = [ t.GetASS(pa,aa,ei,ef) for ei in eiArray ]
    ave= [ 0.0 for ei in eiArray ]

    EC = mm.ElementContainer()

    eid = (eiArray[1] - eiArray[0])
    eiArray = [val - eid * 0.5 for val in eiArray]
    eiArray.append(eiArray[-1]+eid)

    EC.Add("x",eiArray)
    EC.Add("y",av)
    EC.Add("e",ave)
    EC.SetKeys("x","y","e")

    return EC
#-------------------------------------------------------------------------------------------------
def ExecPolyFitEC(ec,degree):

    ecX0 = ec.PutXList()
    ecX  = (( numpy.array(ecX0)[1:] + numpy.array(ecX0)[:-1])*0.5).tolist()
    ecY  = ec.PutYList()

    param  = ExecPolyFit(ecX,ecY,degree)


    ecXnew = numpy.arange(ecX[0],ecX[-1],(ecX[-1]-ecX[0])/100.0)

    ecYnew = PolyFunction(ecXnew,param).tolist()
    ecXnew -= (ecXnew[1] - ecXnew[0])*0.5
    ecXnew = numpy.hstack([ecXnew,numpy.array([ecXnew[-1]+(ecXnew[1] - ecXnew[0])])]).tolist()

    ecEnew = [0]*len(ecYnew)

    ecOut= mm.ElementContainer()

    ecOut.Add("x",ecXnew)
    ecOut.Add("y",ecYnew)
    ecOut.Add("e",ecEnew)

    ecOut.SetKeys("x","y","e")

    return ecOut
#-------------------------------------------------------------------------------------------------
def PutScatteringCrossSectionFactor():
    return 1
#-------------------------------------------------------------------------------------------------
def _checkListDepth(val,i=0):
    if isinstance(val,(list,tuple,dict)) > 0:
        i = _checkListDepth(val[0],i) + 1
    else:
        pass
    return i
#-------------------------------------------------------------------------------------------------
