import sys
import os.path as path

build_dir = path.join(path.dirname(__file__), '..', 'build')
print('Adding build directory to sys.path:', build_dir)
sys.path.append(build_dir)

import slopefit as sf
import numpy as np
import matplotlib.pyplot as plt


fl = 1200.0 # mm
theta_mrad = 3.0 # mrad
theta_rad = theta_mrad * 1e-3
theta = theta_rad / np.pi * 180.0 # deg

parab = sf.ParabolaParams(fl, theta)

filename = 'microMAX_vsru_mispu_absum.dat'
dirname = path.dirname(__file__)

data = sf.import_dat_file(path.join(dirname, filename))

# flip both x and y
data[:, 0] = -data[:, 0]
data[:, 1] = -data[:, 1]

n_skip = 20
data = data[n_skip:-n_skip, :]

ref = parab(data[:, 0])

# convert ref from slope to rad
# ref = np.arctan(ref)
# convert to arcsec
# ref = ref / np.pi * 180.0 * 3600.0


plt.plot(data[:, 0], data[:, 1], 'x')
plt.plot(data[:, 0], ref, '-')
plt.xlabel('x (mm)')
plt.ylabel('slope (arcsec)')
plt.show()

d_parab = sf.ParabolaParams(100.0, 0.00001)

fitted = sf.fit_parabola(data, parab, d_parab)

print('Fitted parameters:')
print('fl =', fitted.focal_length)
print('theta =', fitted.theta * np.pi * 1e3 / 180.0, 'mrad')

fitted_ref = fitted(data[:, 0])

plt.plot(data[:, 0], data[:, 1], 'x')
plt.plot(data[:, 0], fitted_ref, '-')
plt.xlabel('x (mm)')
plt.ylabel('slope (arcsec)')
plt.show()