import numpy as np
from sklearn.model_selection import LeaveOneOut
from sklearn.metrics import mean_squared_error, r2_score
from math import sqrt
from colorama import Fore, Back, Style
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

input_file = 'data'
output_fig = 'graph.png'

def fit(x_train, y_train, x_test, y_test, deg):
    '''Fits a polynomial of a specified degree to the training data
       and computes the RMSE of the polynomial on the test data
    '''
    p = np.polyfit(x_train, y_train, deg)
    y_est = np.polyval(p, x_test)
    rmse = sqrt(mean_squared_error(y_test, y_est))
    return p, rmse

def cv(x, y, deg):
    '''Determines the overall RMSE from leave-one-out cross-validation'''
    loo = LeaveOneOut()
    rmse_arr = np.array([])
    for train_index, test_index in loo.split(x):
        x_train, x_test = x[train_index], x[test_index]
        y_train, y_test = y[train_index], y[test_index]
        p, rmse = fit(x_train, y_train, x_test, y_test, deg)
        rmse_arr = np.append(rmse_arr, rmse)

    return np.mean(rmse_arr**2)

def color(val, rmse):
    '''Returns an ANSI color escape sequence depending on whether a value
       exceeds the RMSE
    '''
    if abs(val) >= 2 * rmse:
        return Fore.RED
    
    if abs(val) >= rmse:
        return Fore.YELLOW
    
    return Fore.GREEN

def poly_str(p):
    '''Returns a matplotlib string representing a polynomial with coefficients p'''
    string = '$y={:.4f}{}'.format(p[0], pow_str(len(p) - 1))
    for i in range(1, len(p)):
        string += '{:+.4f}{}'.format(p[i], pow_str(len(p) - 1 - i))

    return string + '$'

def pow_str(n):
    '''Returns a string representing x^n'''
    if n == 0:
        return ''

    if n == 1:
        return 'x'

    return 'x^{}'.format(n)

if __name__ == '__main__':
    print('SUPER DUPER CURVE FITTER')
    print('by An Le')
    print('-------------------------------------------------------------')
    print()
    print('Loading data...')
    data = np.genfromtxt(input_file)
    ordered = data[np.argsort(data[:,0])]
    lvdt_v, gap_mm = ordered.T
    print()
    print('Finding the best degree of polynomial for regression...')
    print()
    baseline = cv(lvdt_v, gap_mm, 0)
    curr_deg = best_deg = 1
    curr_err = best_err = baseline
    while curr_deg < min(8, len(lvdt_v)) and curr_err <= baseline:
        curr_err = cv(lvdt_v, gap_mm, curr_deg)
        if curr_err < best_err:
            best_deg, best_err = curr_deg, curr_err

        print('Cross-validation - degree {}: {}'.format(curr_deg, curr_err))
        curr_deg += 1

    print()
    print('Fitting degree {} polynomial to data...'.format(best_deg))
    p, rmse = fit(lvdt_v, gap_mm, lvdt_v, gap_mm, best_deg)
    print()
    print('The coefficients are:')
    print()
    for i in range(len(p)):
        letter = chr(65 + i)
        print('{} = {}'.format(letter, p[-i - 1]))

    print()
    print('95% prediction interval: ±{:.3f} mm'.format(1.96 * rmse))
    print('-------------------------------------------------------------')
    print()
    print('Error analysis:')
    print()
    gap_mm_est = np.polyval(p, lvdt_v)
    r2 = r2_score(gap_mm, gap_mm_est)
    err = gap_mm_est - gap_mm
    print('{:>15}{:>15}{:>15}{:>15}'.format('LVDT volt. (V)', 'Est. gap (mm)', 'Act. gap (mm)', 'Error (mm)'))
    for i in range(len(lvdt_v)):
        print('{:15.4f}{:15.4f}{:15.4f}{}{:15.4f}{}'.format(lvdt_v[i], gap_mm_est[i], gap_mm[i], color(err[i], rmse), err[i], Style.RESET_ALL))

    print()
    print('Preparing graph...')
    x = np.linspace(-10, 10, 100)
    y = np.polyval(p, x)
    plt.grid()
    plt.plot(x, y)
    plt.plot(lvdt_v, gap_mm, 'o', markersize=4)
    plt.title('Gap vs. LVDT Voltage')
    plt.xlabel('LVDT analog input voltage (V)')
    plt.ylabel('CMM-measured gap (mm)')
    plt.text(-4.5, 110, poly_str(p), fontsize=8)
    plt.text(-4.5, 105, '$R^2={:.4f}$'.format(r2), fontsize=8)
    print('Saving graph to {}...'.format(output_fig))
    plt.savefig(output_fig, dpi=300)
