"""
Example 9

- evaluate the effects due to misalignment in the undulator line
- discrepancy in K values / phase mismatch in the drift section
"""

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 alignment
simplex.StartSimulation(folder="./output", prefix="sample9", serial=0)

Ncases = 4
simplex.Set("alignment", "ualign", "Specify Tolerance")
# K-value tolerance scanned from 2e-3 to 8e-3
simplex.Scan("alignment", "Ktol", 2e-3, 8e-3, Ncases, link=True, serial=1, iniSN=1)

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

# plot and compare the results
simplex.PostProcess.PlotGainCurve("Pulse Energy")
simplex.PostProcess.SelectData("sample9-0")
simplex.PostProcess.ComparativePlot(*datanames)
simplex.PostProcess.DuplicatePlot("Gain reduction by the K value discrepancy between segments")

# slippage tolerance scanned from 30 deg. to 120 deg.
simplex.Scan("alignment", "sliptol", 30, 120, Ncases, link=True, serial=2, iniSN=1)

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

simplex.PostProcess.PlotGainCurve("Pulse Energy")
simplex.PostProcess.SelectData("sample9-0")
simplex.PostProcess.ComparativePlot(*datanames)
simplex.PostProcess.DuplicatePlot("Gain reduction by the mismatched phase between segments")

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