import sys
import numpy as np
import openpyxl
import pandas as pd
import matplotlib.pyplot as plt


norder = 3
infile  =  'random-poly.xlsx'

fontsize = 16


argv = sys.argv
narg = len(argv)
if narg >= 2:
    infile = argv[1]
if narg >= 3:
    norder = int(argv[2])


def main():
    print("")
    print(f"Read [{infile}]")
    df = pd.read_excel(infile, engine = 'openpyxl')
    labels = df.columns.to_list()
    x = df[labels[0]]
    y = df[labels[1]]
    ndata = len(x)

    print("")
    print(f"Execute linear least-squares method")
    ci = np.polyfit(x, y, norder)
    print(f"ci={ci}")

    ycal =  np.poly1d(ci)(x)

#================================================================
# Plot
#================================================================
    fig, axes = plt.subplots(1, 2, figsize = (8, 6))
    axes[0].plot(x, y,    label = 'input', linestyle = '', marker = 'o')
    axes[0].plot(x, ycal, label = 'fit',   linestyle = '-')
    axes[0].tick_params(labelsize = fontsize)
    axes[0].set_xlabel('$x$', fontsize = fontsize)
    axes[0].set_ylabel('$y$', fontsize = fontsize)
    axes[0].legend(fontsize = fontsize)

    plt.show()


if __name__ == "__main__":
    main()
