"""
Example 5

- import a data file (magnetic distribution of an undulator)
- check the phase error and compare with an ideal case
"""

import time

if __name__ == "__main__":
    import spectra 
    spectra.Start()

spectra.Open("sample.json") 
spectra.SelectBL("X-ray-BL")
spectra.SelectCalculation("near", "energy", "fdenss")

# calculation with an ideal condition
spectra.StartCalculation(folder="./output", prefix="sample5", serial=1)

# evaluate the effects due to a randome field error
# change the source type
spectra.Set("src", "type", "User Defined")
# set the unit (longitudinal coordinate in m)
spectra.PreProcess.SetUnit("zpos", "m")
# import the undualtor data with a random error
spectra.PreProcess.Import("Field Profile", "uerror_model.dat")

# evaluate the electron orbit and phase error
spectra.PreProcess.Plot("2nd Integral")
spectra.PreProcess.DuplicatePlot("Electron Orbit")
spectra.PreProcess.Plot("Phase Error")
spectra.PreProcess.DuplicatePlot("Phase Error")

# calculation with the error condition
spectra.ShowMain()
spectra.StartCalculation()

# compare the result
spectra.PostProcess.Plot("Flux Density")
spectra.PostProcess.SelectData("sample5-1")
spectra.PostProcess.ComparativePlot("sample5-2")
spectra.PostProcess.PlotScale(y="log")

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