''' Suggested solution for Exercise 18.8 '''

# from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from python18_examples import vehicles
from python18_2 import fct

y, x1, x2, x3, x4 = vehicles()
Xin = np.concatenate((x1,x2,x3,x4),axis=1)

[X, beta, yhat, ybar, Syy, SSE, SSR, R2] =  fct(Xin,y)

print('\nResult of multiple regression (all variables included in the model):')
print(' beta0 =', "{0:.4f}".format(beta[0][0]))
print(' beta1 =', "{0:.4f}".format(beta[1][0]))
print(' beta2 =', "{0:.4f}".format(beta[2][0]))
print(' beta3 =', "{0:.4f}".format(beta[3][0]))
print(' beta4 =', "{0:.4f}".format(beta[4][0]))
print(' R^2(beta1,beta2,beta3,beta4) =', "{0:.4f}".format(R2))

'''sequentiel partition: 
    beta1 -> beta1, beta2 -> beta1, beta2, beta3 -> beta1, beta2, beta3, beta4
'''

Xin1 = x1
Xin12 = np.concatenate((x1,x2),axis=1)
Xin123 = np.concatenate((x1,x2,x3),axis=1)
Xin1234 = np.concatenate((x1,x2,x3,x4),axis=1)


[X, beta, yhat, ybar, Syy, SSE, SSR, R21] =  fct(Xin1,y)
[X, beta, yhat, ybar, Syy, SSE, SSR, R212] =  fct(Xin12,y)
[X, beta, yhat, ybar, Syy, SSE, SSR, R2123] =  fct(Xin123,y)
[X, beta, yhat, ybar, Syy, SSE, SSR, R21234] =  fct(Xin1234,y)

print('\nCoefficients of determination of the 4 models:')
print(' R^2(beta1) =', "{0:.4f}".format(R21))
print(' R^2(beta1, beta2) =', "{0:.4f}".format(R212))
print(' R^2(beta1, beta2, beta3) =', "{0:.4f}".format(R2123))
print(' R^2(beta1, beta2, beta3, beta4) =', "{0:.4f}".format(R21234))

print('\nSequential partial coefficients of determination:')
print(' R^2(beta1) =', "{0:.4f}".format(R21))
print(' R^2(beta2|beta1) =', "{0:.4f}".format(R212 - R21))
print(' R^2(beta3|beta1, beta2) =', "{0:.4f}".format(R2123 - R212))
print(' R^2(beta4|beta1, beta2, beta3) =', "{0:.4f}".format(R21234 - R2123))
print(' Unexplained by regression =', "{0:.4f}".format(1 - R2))

''' pie chart for proportions '''
pp = [R21, R212-R21, R21234-R2123, 1 - R2]
'''The proportion of beta3 = R2123 - R212 has been removed; it equals = 0.0001.
   This would disturb the caption of the plot otherwise''' 

plt.figure()
plt.pie(pp)
plt.axis('equal')
plt.legend(['proportion beta1','proportion beta2', 'proportion beta4', 
                    'unexplained'], loc="best")
plt.show()

#raw_input()