from __future__ import print_function
import time
import os,sys
import Manyo as mm
import Manyo.Utsusemi as mu
import Manyo.LevmarTools as ml
import math
import uGao.MPlot as mp
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

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

def PeakFitBase(ec,function,param,param_ub,param_lb,fit_region,useDomain,NumOfItteration,plotflug,useWeight):
    """
    PeakFitting script by using Levmar, AS Fit
    @param ec    (ElementContainer)
    @param function        (string)
    @param param           (string)
    @param param_lb        (string)
    @param param_ub        (string)
    @param useDomain       (bool)
    @param NumOfItteration (int)
    @param plotflug        (bool)
    @param useWeight       (bool)
    """
    x_bin = ec.PutX()
    binwidth = (x_bin[1]-x_bin[0])

    param_init_string = param.split(",")
    param_ub_string   = param_ub.split(",")
    param_lb_string   = param_lb.split(",")
    fit_region_string = fit_region.split(",")
    xbin_start = float(fit_region_string[0])
    xbin_end = float(fit_region_string[1])

    param_init = []
    param_ub = []
    param_lb = []

    for i in range(len(param_init_string)):
         param_init.append(float(param_init_string[i]))
         param_ub.append(float(param_ub_string[i]))
         param_lb.append(float(param_lb_string[i]))

    op = ml.AdvPeakFit(ec,ml.NEW_LEVMAR)
    if useDomain:
         op.setParam(ml.AdvNewLevmar.CONSTRAIN,          ml.AdvNewLevmar.BOX)
    else:
         op.setParam(ml.AdvNewLevmar.CONSTRAIN,          ml.AdvNewLevmar.NO_CONSTRAIN)
    op.setParam(ml.AdvNewLevmar.USE_NUMERICAL_DIFF, False)
    op.setParam(ml.AdvNewLevmar.DIFF_METHOD,        ml.AdvNewLevmar.FORWARD)
    op.setParam(ml.AdvNewLevmar.USE_DATA_WEIGHTS,   useWeight)
    op.setParam(ml.AdvNewLevmar.MAX_ITERATIONS,     NumOfItteration)
    op.setParam(ml.AdvNewLevmar.OUTPUT_INTERVAL,    1000)
    op.setParam(ml.AdvNewLevmar.FUNCTIONS, function)
    op.setParam(ml.AdvNewLevmar.PARAMETER_VALUES, param_init)
    op.setParam(ml.AdvNewLevmar.LOWER_BOUNDS, param_lb)
    op.setParam(ml.AdvNewLevmar.UPPER_BOUNDS, param_ub)

    i1 = ( xbin_start - x_bin[0] ) / binwidth
    i2 = ( xbin_end - x_bin[0] ) / binwidth
    if i1 < 0 :
        i1 = 0
    if i1 >= x_bin.size():
        i1 = x_bin.size() - 2
    if i2 < 0 :
        i2 = 0
    if i2 >= x_bin.size():
        i2 = x_bin.size() - 2
  
    op.setDomain(int(i1),int(i2))

    op.fit()
    size_p = len(param_init_string)
 #   if useDomain:
 #       sleep_time = int(size_p*size_p*NumOfItteration/10000*1.5)
 #       sleep_time = 1
 #   else:
 #       sleep_time = 1
 #   time.sleep(5)

    while op.isFitting():
        time.sleep(0.5)


    op.eval()

    result=op.getResult()
    fittedParam=op.getFittedParam()

    basepath = os.path.join(os.environ["MLF_USR_DIR"],"tmp")
    filepath = os.path.join(basepath,"fit_result.txt")
    filebkpath = os.path.join(basepath,"fit_result_bk.txt")

    fileflug = os.path.exists(filepath)
    if fileflug:
        os.rename(filepath,filebkpath)
    fw = open(filepath, 'w')
    x_result = result.PutX()
    y_result = result.PutY()
    for i in range(len(y_result)):
        fw.write(str((x_result[i]+x_result[i+1])/2)+"\t"+str(y_result[i])+"\n")
    fw.close()

    s=fittedParam.getVectorSize(ml.AdvNewLevmar.PARAMETER_VALUES)
    param_result = []
    param_result_error = []

    LatestConvStat=op.getLatestConvergenceStat()
    chi = LatestConvStat.getDouble(ml.AdvNewLevmar.RESIDUAL_ERR_NORM)

    for i in range(s):
        param_result.append(fittedParam.getDouble(ml.AdvNewLevmar.PARAMETER_VALUES,i))
        param_result_error.append(fittedParam.getDouble(ml.AdvNewLevmar.PARAM_ERRORS,i))

    if plotflug:
        p = mp.MPlot()
        p.AddData(result)

        p.SetPlotParam(1,ls="-",lw=8,mk="",eb=False)
        p.AddData(ec)

        s=fittedParam.getVectorSize(ml.AdvNewLevmar.PARAMETER_VALUES)

        param_result = []
        param_result_error = []
        print("##############################################################")
        print(" Fit Result (",function,")")
        for i in range(s):
            pr = fittedParam.getDouble(ml.AdvNewLevmar.PARAMETER_VALUES,i)
            pre = fittedParam.getDouble(ml.AdvNewLevmar.PARAM_ERRORS,i)
            param_result.append(pr)
            param_result_error.append(pre)
            print("param%i\t%.2e\t::: param%i Error\t%.2e"%(i,pr,i,pre))
        print("##############################################################")

    return param_result,param_result_error,chi,result



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

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

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

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

def PeakFitSimple(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,peak_back,xbin_start,xbin_end,useDomain,flug,flug3):
    """
    PeakFitting script by using Levmar,gauss+constant AS Fit
    @param ec (ElementContainer)
    @param func               (string)
    @param fit_boundary_ratio (float)
    @param peak_hight         (float)
    @param peak_position      (float)
    @param peak_fwhm          (float)
    @param peak_back          (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    @param flug                (bool)
    @param flug3                (bool)
    """
    import datetime as dt
    x_bin = ec.PutX()
    binwidth = x_bin[1]-x_bin[0]

    op = ml.AdvPeakFit(ec,ml.NEW_LEVMAR)

    param = str(peak_hight)+","+str(peak_position)+","+str(peak_fwhm)+","+str(peak_back)
    param_lb = str(peak_hight-abs(peak_hight*fit_boundary_ratio)-100)+","+str(peak_position-abs(peak_position*fit_boundary_ratio)-1000)+","+str(peak_fwhm-abs(peak_fwhm*fit_boundary_ratio))+","+str(peak_back-abs(peak_back*fit_boundary_ratio)-100)
    param_ub = str(peak_hight+abs(peak_hight*fit_boundary_ratio)+100)+","+str(peak_position+abs(peak_position*fit_boundary_ratio)+1000)+","+str(peak_fwhm+abs(peak_fwhm*fit_boundary_ratio))+","+str(peak_back+abs(peak_back*fit_boundary_ratio)+100)
    fit_region = str(xbin_start) +","+str(xbin_end)

    if flug:
        plotflug =False
    else:
        plotflug =True
    param_result,param_result_error,result = PeakFit(ec,func,param,param_ub,param_lb,fit_region,useDomain,10000,plotflug)
#
#    x = result.PutXList()
#   x = ECToLinear( x )
#    result.Add( result.PutXKey(), x )
#
    S = param_result[0]*param_result[2]*math.sqrt(math.pi/math.log(2))/binwidth
    S_error = param_result[0]*param_result[2]*math.sqrt((param_result_error[0]/param_result[0])**2+(param_result_error[2]/param_result[2])**2)*math.sqrt(math.pi/math.log(2))/binwidth

    S_back = param_result[3]/binwidth*(xbin_end-xbin_start)
    S_back_error = param_result_error[3]/binwidth*(xbin_end-xbin_start)

    fwhm = param_result[2]*2
    fwhm_error = param_result_error[2]*2

    r_position = param_result[1]
    r_position_error = param_result_error[1]

    peak_intensity = param_result[0]
    peak_intensity_error = param_result_error[0]

    gross_count = S+S_back
    gross_count_error = math.sqrt(S_error*S_error+S_back_error*S_back_error)

    print("")
    print("////////////////////////////////////////////")
    print("///      Fitting result                  ///")
    print("xbin_start     = %.2f"%(xbin_start))
    print("xbin_end       = %.2f"%(xbin_end))
    print("peak intensity = %.2e, error = %.2e"%(peak_intensity,peak_intensity_error))
    # print "gross count    = %.2e, error = %.2e"%(gross_count,gross_count_error)
    # print "back count     = %.2e, error = %.2e"%(S_back,S_back_error)
    # print "net count      = %.2e, error = %.2e"%(S,S_error)
    print("fwhm           = %.2e, error = %.2e"%(fwhm,fwhm_error))
    print("peak_position  = %.2e, error = %.2e"%(r_position,r_position_error))
    print("Constant_back  = %.2e, error = %.2e"%(param_result[3],param_result_error[3]))
    print("////////////////////////////////////////////")

    result_phys = []
    result_phys.append(S)
    result_phys.append(S_error)
    result_phys.append(fwhm)
    result_phys.append(fwhm_error)
    result_phys.append(peak_intensity)
    result_phys.append(peak_intensity_error)

    day=dt.datetime.now()

    filename = "FitInfo"+str(day.year)+"_"+str(day.month)+"_"+str(day.day)+".txt"
    #filepath = os.path.join(os.environ["HOME"],"ana","tmp",filename)
    filepath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp",filename)
    flug2 = os.path.exists(filepath)

    if flug2 == False:
        fw = open(filepath, 'w')
        fw.write('time\tNo\txbin_start\txbin_end\tpeak_intensity\terror\tgross_count\terror\tback_count\terror\tnet_count\terror\tFWHM\terror\tnote\n')
        line_num=1
    else:
        fr = open(filepath, 'r')
        line_num = len(fr.readlines())
        fr.close()
        fw = open(filepath, 'a')

    fw.write(str(day.hour)+":"+str(day.minute)+":"+str(day.second))
    fw.write("\t%.i\t%.2f\t%.2f\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t"%(line_num,xbin_start,xbin_end,peak_intensity,peak_intensity_error,gross_count,gross_count_error,S_back,S_back_error,S,S_error,fwhm,fwhm_error))
    note = ""
    fw.write(note+"\n")  
    fw.close()

    result_x = []
    result_y = []
    result_e =[]
    initial=int(xbin_start/binwidth*4)
    final= int(xbin_end/binwidth*4)
    delta = 1
    if func=="g c":
       func1=ml.AdvGaussian()
    elif func=="erf c":
#       func1=ml.AdvErrorFunction()
       func1=ml.AdvGaussian()
    elif func=="l c":
       func1=ml.AdvLorentzian()
    for i in range(initial,final,delta):
         result_x.append((i-delta*0.5)*binwidth/4)
         result_y.append(func1.eval(((i-delta*0.5)*binwidth/4),param_result[0],param_result[1],param_result[2])+param_result[3])
         result_e.append(0)
    result_x.append((final+delta*0.5)*binwidth/4)

    result2 = mm.ElementContainer()
    result2.Add("x",result_x)
    result2.Add("y",result_y)
    result2.Add("e",result_e)
    result2.SetKeys("x","y","e")
    if flug3:
        if flug:
            p = mp.MPlot()
            p.AddData(ec)
            if func == "erf c":
                 p.AddData(result)
            else:
                 p.AddData(result2)        
            xscale_start = xbin_start
            xscale_end = xbin_end

            p.SetXScale(xscale_start-abs((xscale_end-xscale_start)*0.2),xscale_end+abs((xscale_end-xscale_start)*0.2))
            #p.SetYScale(-1000,10000)

            p.SetLog(True)
            p.SetPlotParam(1,ls="-",lw=8,mk="",eb=False)
            p.SetPlotParam(2,ls="-",lw=10,mk="",eb=False)

    return result2,result_phys

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

def PeakFitSimple0(ec,func,fit_boundary_ratio,peak_hight,peak_position,peak_fwhm,xbin_start,xbin_end,useDomain,flug):
    """
    PeakFitting script by using Levmar, gauss, AS Fit
    @param ec (ElementContainer)
    @param func               (string)
    @param fit_boundary_ratio (float)
    @param peak_hight         (float)
    @param peak_position      (float)
    @param peak_fwhm          (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    @param flug                (bool)
    """
    x_bin = ec.PutX()
    binwidth = x_bin[1]-x_bin[0]

    param = str(peak_hight)+","+str(peak_position)+","+str(peak_fwhm)
    param_lb = str(peak_hight-abs(peak_hight*fit_boundary_ratio)-100)+","+str(peak_position-abs(peak_position*fit_boundary_ratio)-1000)+","+str(peak_fwhm-abs(peak_fwhm*fit_boundary_ratio))
    param_ub = str(peak_hight+abs(peak_hight*fit_boundary_ratio)+100)+","+str(peak_position+abs(peak_position*fit_boundary_ratio)+1000)+","+str(peak_fwhm+abs(peak_fwhm*fit_boundary_ratio))
    fit_region = str(xbin_start) +","+str(xbin_end)

    param_result,param_result_error,result = PeakFit(ec,func,param,param_ub,param_lb,fit_region,useDomain,10000,True)

    import datetime as dt

    S = param_result[0]*param_result[2]*math.sqrt(math.pi/math.log(2))/binwidth
    S_error = param_result[0]*param_result[2]*math.sqrt((param_result_error[0]/param_result[0])**2+(param_result_error[2]/param_result[2])**2)*math.sqrt(math.pi/math.log(2))/binwidth

    S_back = 0
    S_back_error = 0

    fwhm = param_result[2]*2
    fwhm_error = param_result_error[2]*2

    peak_intensity = param_result[0]
    peak_intensity_error = param_result_error[0]

    r_position = param_result[1]
    r_position_error = param_result_error[1]

    gross_count = S+S_back
    gross_count_error = math.sqrt(S_error*S_error+S_back_error*S_back_error)

    print("")
    print("////////////////////////////////////////////")
    print("///      Fitting result                  ///")
    print("xbin_start     = %.2f"%(xbin_start))
    print("xbin_end       = %.2f"%(xbin_end))
    print("peak intensity = %.2e, error = %.2e"%(peak_intensity,peak_intensity_error))
    # print "gross count    = %.2e, error = %.2e"%(gross_count,gross_count_error)
    # print "back count     = %.2e, error = %.2e"%(S_back,S_back_error)
    # print "net count      = %.2e, error = %.2e"%(S,S_error)
    print("fwhm           = %.2e, error = %.2e"%(fwhm,fwhm_error))
    print("peak_position  = %.2e, error = %.2e"%(r_position,r_position_error))
    print("////////////////////////////////////////////")


    result_phys = []
    result_phys.append(S)
    result_phys.append(S_error)
    result_phys.append(fwhm)
    result_phys.append(fwhm_error)
    result_phys.append(peak_intensity)
    result_phys.append(peak_intensity_error)

    day=dt.datetime.now()

    filename = "FitInfo"+str(day.year)+"_"+str(day.month)+"_"+str(day.day)+".txt"
    filepath = os.path.join(os.environ["HOME"],"ana","tmp",filename)
    flug2 = os.path.exists(filepath)

    if flug2 == False:
        fw = open(filepath, 'w')
        fw.write('time\tNo\txbin_start\txbin_end\tpeak_intensity\terror\tgross_count\terror\tback_count\terror\tnet_count\terror\tFWHM\terror\tnote\n')
        line_num=1
    else:
        fr = open(filepath, 'r')
        line_num = len(fr.readlines())
        fr.close()
        fw = open(filepath, 'a')

    fw.write(str(day.hour)+":"+str(day.minute)+":"+str(day.second))
    fw.write("\t%.i\t%.2f\t%.2f\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t%.2e\t"%(line_num,xbin_start,xbin_end,peak_intensity,peak_intensity_error,gross_count,gross_count_error,S_back,S_back_error,S,S_error,fwhm,fwhm_error))
    note = ""
    fw.write(note+"\n")  
    fw.close()

    result_x = []
    result_y = []
    result_e =[]
    initial=float(xbin_start)
    final= float(xbin_end)
    delta = (initial-final)/x_bin.size()/4
    if func=="g":
       func1=ml.AdvGaussian()
    elif func=="erf":
#       func1=ml.AdvErrorFunction()
       func1=ml.AdvGaussian()
    elif func=="l":
       func1=ml.AdvLorentzian()
    for i in range(initial,final,delta):
         result_x.append(i-delta*0.5)
         result_y.append(func1.eval(i,param_result[0],param_result[1],param_result[2]))
         result_e.append(0)
    result_x.append(final+delta*0.5)

    result2 = mm.ElementContainer()
    result2.Add("x",result_x)
    result2.Add("y",result_y)
    result2.Add("e",result_e)
    result2.SetKeys("x","y","e")

    if flug:
        p = mp.MPlot()
        p.AddData(ec)
        if func == "erf":
             p.AddData(result)
        else:
             p.AddData(result2)        
        xscale_start = xbin_start - abs((param_result[1]-xbin_start)*0.1)
        xscale_end = xbin_end + abs((param_result[1]-xbin_end)*0.1)

        p.SetXScale(xscale_start,xscale_end)
        p.SetPlotParam(2,ls="-",lw=8,mk="",eb=False)
   
    return result2,result_phys


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

def PeakFitTriTrape(ec,func,fit_boundary_ratio,hight,boundary,background,xbin_start,xbin_end,useDomain,flug,flug3):
    """
    PeakFitting script by using Levmar,gauss+constant AS Fit
    @param ec (ElementContainer)
    @param func               (string)
    @param fit_boundary_ratio (float)
    @param hight              (float)
    @param boundary         (string)
    @param background         (float)
    @param xbin_start         (float)
    @param xbin_end           (float)
    @param useDomain           (bool)
    @param flug                (bool)
    @param flug3                (bool)
    """
    import datetime as dt
    x_bin = ec.PutX()
    binwidth = x_bin[1]-x_bin[0]

    op = ml.AdvPeakFit(ec,ml.NEW_LEVMAR)

    boundary_param=boundary.split(",")
    boundary_1=float(boundary_param[0])
    boundary_2=float(boundary_param[1])
    boundary_3=float(boundary_param[2])

    if func == "tri c":
        param = str(hight)+","+str(boundary_1)+","+str(boundary_2)+","+str(boundary_3)+","+str(background)
        param_lb = str(hight-abs(hight*fit_boundary_ratio)-10)+","+str(boundary_1-abs(boundary_1*fit_boundary_ratio)-10)+","+str(boundary_2-abs(boundary_2*fit_boundary_ratio)-10)+","+str(boundary_3-abs(boundary_3*fit_boundary_ratio)-10)+","+str(background-abs(background*fit_boundary_ratio)-10)
        param_ub = str(hight+abs(hight*fit_boundary_ratio)+10)+","+str(boundary_1+abs(boundary_1*fit_boundary_ratio)+10)+","+str(boundary_2+abs(boundary_2*fit_boundary_ratio)+10)+","+str(boundary_3+abs(boundary_3*fit_boundary_ratio)+10)+","+str(background+abs(background*fit_boundary_ratio)+10)

    if func == "trp c":
        boundary_4=float(boundary_param[3])
        param = str(hight)+","+str(boundary_1)+","+str(boundary_2)+","+str(boundary_3)+","+str(boundary_4)+","+str(background)
        param_lb = str(hight-abs(hight*fit_boundary_ratio)-10)+","+str(boundary_1-abs(boundary_1*fit_boundary_ratio)-10)+","+str(boundary_2-abs(boundary_2*fit_boundary_ratio)-10)+","+str(boundary_3-abs(boundary_3*fit_boundary_ratio)-10)+","+str(boundary_4-abs(boundary_4*fit_boundary_ratio)-10)+","+str(background-abs(background*fit_boundary_ratio)-10)
        param_ub = str(hight+abs(hight*fit_boundary_ratio)+10)+","+str(boundary_1+abs(boundary_1*fit_boundary_ratio)+10)+","+str(boundary_2+abs(boundary_2*fit_boundary_ratio)+10)+","+str(boundary_3+abs(boundary_3*fit_boundary_ratio)+10)+","+str(boundary_4+abs(boundary_4*fit_boundary_ratio)+10)+","+str(background+abs(background*fit_boundary_ratio)+10)
    fit_region = str(xbin_start) +","+str(xbin_end)

    if flug:
        plotflug =False
    else:
        plotflug =True
    param_result,param_result_error,result = PeakFit(ec,func,param,param_ub,param_lb,fit_region,useDomain,10000,plotflug)
#
#    x = result.PutXList()
#   x = ECToLinear( x )
#    result.Add( result.PutXKey(), x )
#

    print("")
    print("////////////////////////////////////////////")
    print("///      Fitting result                  ///")
    print("xbin_start     = %.2f"%(xbin_start))
    print("xbin_end       = %.2f"%(xbin_end))
    print("hight = %.2e, error = %.2e"%(param_result[0],param_result_error[0]))
    print("boundary_1  = %.2e, error = %.2e"%(param_result[1],param_result_error[1]))
    print("boundary_2  = %.2e, error = %.2e"%(param_result[2],param_result_error[2]))
    print("boundary_3  = %.2e, error = %.2e"%(param_result[3],param_result_error[3]))
    if func == "tri c":
         print("background  = %.2e, error = %.2e"%(param_result[4],param_result_error[4]))
    if func == "trp c":
         print("boundary_4  = %.2e, error = %.2e"%(param_result[4],param_result_error[4]))
         print("background  = %.2e, error = %.2e"%(param_result[5],param_result_error[5]))
    print("////////////////////////////////////////////")

    result_x = []
    result_y = []
    result_e =[]
    initial=int(xbin_start/binwidth*4)
    final= int(xbin_end/binwidth*4)
    delta = 1

    if func == "tri c":
        func1=ml.AdvTriangle()
        for i in range(initial,final,delta):
             result_x.append((i-delta*0.5)*binwidth/4)
             result_y.append(func1.eval(((i-delta*0.5)*binwidth/4),param_result[0],param_result[1],param_result[2],param_result[3])+param_result[4])
             result_e.append(0)
        result_x.append((final+delta*0.5)*binwidth/4)

    if func == "trp c":
        func1=ml.AdvTrapezoid()
        for i in range(initial,final,delta):
             result_x.append((i-delta*0.5)*binwidth/4)
             result_y.append(func1.eval(((i-delta*0.5)*binwidth/4),param_result[1],param_result[2],param_result[3],param_result[4],param_result[0])+param_result[5])
             result_e.append(0)
        result_x.append((final+delta*0.5)*binwidth/4)


    result2 = mm.ElementContainer()
    result2.Add("x",result_x)
    result2.Add("y",result_y)
    result2.Add("e",result_e)
    result2.SetKeys("x","y","e")
    if flug3:
        if flug:
            p = mp.MPlot()
            p.AddData(ec)
            if func == "erf c":
                 p.AddData(result)
            else:
                 p.AddData(result2)        
            xscale_start = xbin_start
            xscale_end = xbin_end

            p.SetXScale(xscale_start-abs((xscale_end-xscale_start)*0.2),xscale_end+abs((xscale_end-xscale_start)*0.2))

            #p.SetLog(True)
            p.SetPlotParam(2,ls="-",lw=8,mk="",eb=False)
       
