#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

### Define Data
x=np.array([0,20,50,80,120,170],dtype=float)
yT=np.array([100,92.5,82.3,73.6,63.7,53.8],dtype=float)
y = np.log(yT-17.1)
x_err=np.array([1]*6)
y_err=np.array([1]*6)



### Define options
color = 'b'
label='test'
title='Titre du graphe'
xlog=False
ylog=False
xlabel="Axe des absisses"
ylabel="Axe des ordonnées"
lastcolor='r'
reg=True

### Actual program

# Linear regression
def to_minimize(x,y,x_err,y_err,a,b):
    weights=1.0/(x_err**2+y_err**2)
    s=np.sum((a*x+b-y)**2*weights)
    return(s)

def auxiliary(param):
    a,b=param
    return(to_minimize(x,y,x_err,y_err,a,b))

opt=minimize(auxiliary,((y[0]-y[-1])/(x[0]-x[-1]),0))
a,b=opt['x']
sigma=np.sqrt(np.sum((y-a*x+b)**2))
r2=1-(np.sum((y-a*x-b)**2))/(np.sum((y-np.mean(y))**2))

# Plot with color and error bars
if lastcolor:
    plt.errorbar(x[:-1],y[:-1],xerr=x_err[:-1],yerr=y_err[:-1], ecolor=color,color=color,capsize=2,fmt='o',label=label)
    plt.errorbar(x[-1],y[-1],xerr=x_err[-1],yerr=y_err[-1], ecolor=lastcolor,color=lastcolor,capsize=2,fmt='o',label=label+' direct')
else :
    plt.errorbar(x,y,xerr=x_err,yerr=y_err, ecolor=color,color=color,capsize=2,fmt='o',label=label)

if reg:
    plt.plot(np.sort(x),a*np.sort(x)+b,label=r"regression, y={a:.3}x+{b:.3}, r $^2$={r2:1.4f}".format(r2=r2,a=a,b=b))

# Shaping
plt.legend()
plt.title(title)
if xlog:
    plt.xscale("log")

if ylog:
    plt.yscale("log")

plt.grid(which='major',linewidth=1)
plt.grid(which='minor',linewidth=.5,linestyle='--')
plt.xlabel(xlabel)
plt.ylabel(ylabel)

# Show
plt.show()
