"""
Example 8

- calculate a Wigner function on the vertical (y,'y) phase space
- load the Wigner function and perform CMD (coherent mode decomposition)
"""

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

spectra.Open("sample.json")
spectra.SelectBL("X-ray-BL")

# flux spatial profile
spectra.SelectCalculation("srcpoint", "wigner", "phasespace", "YYpprj")

# transverse range auto configuration
spectra.Set("config", "autot", True) 

# compute the Wigner function
spectra.StartCalculation(folder="./output", prefix="sample8", serial=1)

# load the Wigner function for CMD
spectra.LoadWigner4CMD("./output/sample8-1.json")

# export the modal profile with finer grid and wider range
spectra.Set("config", "CMDfld", "JSON") 
spectra.Set("config", "fieldrangey", 0.05) 
spectra.Set("config", "fieldgridy", 0.0005) 

# perform CMD
spectra.StartCalculation(prefix="sample8", serial=2)

# check modal intensity
spectra.PostProcess.SetCategory("Modal Flux")
spectra.PostProcess.Plot("Integrated Modal Flux")
spectra.PostProcess.DuplicatePlot("Integrated Modal Flux")

# check modal intensity
spectra.PostProcess.SetCategory("Modal Profile")
spectra.PostProcess.Plot("Modal Amplitude Real")

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