#import libraries
import pandas as pd
import numpy as np
import statsmodels.api as sm
from matplotlib import pyplot, pylab
import statsmodels.formula.api as smf
import scipy.stats as stats
import sys

# assign variables
filename = sys.argv[1]
prefix = sys.argv[2]


def main():
	
	# load data
	data = pd.read_csv(filename, sep=',')
	
	# run the normality plot function and export them as pdf file
	normalplot_year_ndvi = check_normality_plot(data.Year, data.NDVI,'normality_year_NDVI.pdf')
	normalplot_year_rain = check_normality_plot(data.Year, data.Rain,'normality_year_Rain.pdf')
	normalplot_year_temp = check_normality_plot(data.Year, data.Temperature,'normality_year_Temp.pdf')
	normalplot_ndvi_temp = check_normality_plot(data.NDVI, data.Temperature,'normality_NDVI_Temp.pdf')
	normalplot_ndvi_rain = check_normality_plot(data.NDVI, data.Rain,'normality_NDVI_Rain.pdf')



def check_normality_plot(x ,y, savefile):
    '''checking the normality condition for linear regression by using a qqplot
    Input: independent variable (x), dependent variable (y), and savefile name
    Output: QQ-plot based on the input variables'''
    
    # load data
    data = pd.read_csv(filename, sep=',')
    
    assert len(data) > 1, 'Dataset should have more than one values'
    
    # run the qqplot
    X = sm.add_constant(x)
    mod_fit = sm.OLS(y, x). fit()
    
    assert len(x) > 1, 'Independent variable (x) should have at least two values'
    assert len(y) > 1, 'Dependent variable (y) should have at least two values'
    
    
    res = mod_fit.resid
    fig = sm.qqplot(res, stats.t, fit=True, line='45')
    
    # save plot to the directory that the user inputs
    pyplot.savefig(prefix + savefile)


main()