"""
Example 8

- evaluate the effects due to the trajectory errors on the FEL gain
- visualize the variation of spectral profile
"""

if __name__ == "__main__":
    import simplex 

# start with default settings
# Mode = interactive, Browser = Chrome, Source Files = remote
    simplex.Start() 

# open "sample.json" in the current directory
simplex.Open("sample_sase.json") 

# ideal trajectory
simplex.StartSimulation(folder="./output", prefix="sample8", serial=0)

# trajectory error due to BPM misalignment
Ncases = 4
simplex.Set("alignment", "BPMalign", "Specify Tolerance")
# BPM alignment tolerance scanned from 5um to 20um
simplex.ScanXY("alignment", "xytol", 5e-3, 0.02, Ncases, link=True, serial=1, iniSN=1)

# data names 
datanames = []
for n in range(Ncases):
    datanames.append("sample8-1"+"_"+str(n+1))

# plot and compare the results
simplex.PostProcess.PlotGainCurve("Pulse Energy")
simplex.PostProcess.SelectData("sample8-0")
simplex.PostProcess.ComparativePlot(*datanames)
simplex.PostProcess.DuplicatePlot("Gain reduction by the BPM misalignment")

# betatron oscillation due to injection error
simplex.Set("alignment", "BPMalign", "Ideal")
simplex.Set("dispersion", "einjec", True)
# injection error scanned from 1urad to 4urad
simplex.ScanXY("dispersion", "exyp", 1e-3, 4e-3, Ncases, link=True, serial=2, iniSN=1)

# data names 
datanames = []
for n in range(Ncases):
    datanames.append("sample8-2"+"_"+str(n+1))

simplex.PostProcess.PlotGainCurve("Pulse Energy")
simplex.PostProcess.SelectData("sample8-0")
simplex.PostProcess.ComparativePlot(*datanames)
simplex.PostProcess.DuplicatePlot("Gain reduction by the injection error")

if __name__ == "__main__":
    input("Completed. Press enter to exit. ")
    simplex.Exit()
    
