import matplotlib.pyplot as plt
import numpy as np

def main():
    directories = [
        "output/relative_error/RK4/",
        "output/relative_error/euler/",
    ]
    files = [
        "4000_steps.txt",
        "8000_steps.txt",
        "16000_steps.txt",
        "32000_steps.txt",
    ]
    labels = [
        r"4000 steps",
        r"8000 steps",
        r"16000 steps",
        r"32000 steps",
    ]
    titles = [
        "Relative error for the RK4 method",
        "Relative error for the forward Euler method"
    ]
    methods = [
        "rk4",
        "euler"
    ]
    fig1, axs1 = plt.subplots(2,1)
    for i, (dir, title) in enumerate(list(zip(directories, titles))):
        max_err = []
        for label, file in zip(labels, files):
            with open(dir+file) as f:
                lines = f.readlines()
                t = np.linspace(0, 50, len(lines))
                r = np.array([float(line.strip()) for line in lines])
                max_err.append(max(r))
                axs1[i].plot(t, r, label=label)
        
        axs1[i].set(xlabel=r"t $(\mu s)$", ylabel = r"relative_error $(\mu m)$")
        axs1[i].legend()
        axs1[i].set_title(title)

        conv_rate = 1/3 * sum([np.log2(max_err[i+1]/max_err[i])/np.log2(.5) for i in range(3)])
        print(f"{methods[i]}: {conv_rate}")

    fig1.savefig("../latex/images/phase_space_2_particles_x.pdf")


if __name__ == "__main__":
    main()
