regression.py

Retour Ă  la liste des codes python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import matplotlib.pyplot as plt
import numpy as np
import random as rd
import csv

# Grandeurs
xname = 't'
xunit = 'years'
yname = 'd'
yunit = 'km'

# Données
uax = 'y'  # axe des incertitudes dominantes
data_live = [
    ]
data_prep = [
    ]
with open('data.csv', newline='') as data:
    reader = csv.reader(data, delimiter=';', quotechar='|')
    for datum in reader:
        x = np.float64(datum[0])
        y = np.float64(datum[1])
        #u = np.float64(datum[2])
        u = y*0.1
        data_prep.append([x, y, u])

data_prep2 = [[x + 10*rd.random(), y + rd.random(), u] for x,y,u in data_prep]

class Data:
    def __init__(self, lists, uax):
        arr = np.array(lists)
        self.x = arr[:, 0]
        self.y = arr[:, 1]
        self.u = arr[:, 2]
        self.uax = uax
    def __iter__(self):
        self.current = 0
        return self
    def __next__(self):
        if self.current >= len(self.x):
            raise StopIteration
        i = self.current
        self.current += 1
        return Data([[self.x[i], self.y[i], self.u[i]]], self.uax)

# Conversion vers classe Data plus exploitable
data = Data(data_prep + data_live, uax)
data2 = Data(data_prep2 + data_live, uax)
if len(data_live) != 0: data_live = Data(data_live, uax)

def plot_data(data, data_highlight=[], reg=True):
    # Plot des points
    if uax == 'x': xerr = data.u; yerr = None;
    elif uax == 'y': xerr = None; yerr = data.u;
    plt.errorbar(
            x=data.x,
            y=data.y,
            xerr=xerr,
            yerr=yerr,
            marker='+', linestyle='None', elinewidth=1)
    # Plot des points mis en évidence
    color = plt.gca().get_lines()[-1].get_color()
    for datum in data_highlight:
        plt.scatter(datum.x, datum.y, color=color, marker='x')
    if reg:
        # Calcul de coefs de régression linéaire
        u = data.u if np.count_nonzero(data.u) > 0 else np.ones(len(data.u))
        S11 = np.sum(1 / (u*u))
        Sxx = np.sum(data.x*data.x / (u*u))
        Syy = np.sum(data.y*data.y / (u*u))
        Sxy = np.sum(data.x*data.y / (u*u))
        Sx1 = np.sum(data.x / (u*u))
        Sy1 = np.sum(data.y / (u*u))

        d = (S11 * Sxx - Sx1*Sx1)
        a = (S11 * Sxy - Sx1 * Sy1) / d
        b = (Sxx * Sy1 - Sx1 * Sxy) / d

        ua = np.sqrt(S11 / d)
        ub = np.sqrt(Sxx / d)

        uainv = np.abs(1/a * (1/a**2)*ua)
        ubinv = np.abs(b/a * np.sqrt((ua*b/a**2)**2 + (ub/a**2)**2))

        chi2 = np.sum(((a*data.x + b - data.y)/data.u)**2)
        chi2red = chi2 / (len(data.x) - 2)

        print("____________________")
        print('Ajustement: {} = a.{} + b'.format(yname, xname))
        print("a = {}({})".format(a, ua))
        print("b = {}({})".format(b, ub))

        print("____________________")
        print('Ajustement: {} = {}/a - b/a'.format(xname, yname))
        print("1/a = {}({})".format(1/a, uainv))
        print("-b/a = {}({})".format(-b/a, ubinv))

        print("____________________")
        print('Chi2 réduit')
        print("chi2red = {}".format(chi2red))

        print("")
        # Calcul de y(predict_x) pour estimer un point sur la droite
        print("____________________")
        print('Prédiction de {}({})'.format(yname, xname))
        predict_x = 4
        predict_y = predict_x * a + b
        upredict_y = np.sqrt((predict_x * ua)**2 + ub**2)
        print("{}({} = {}) = {}({})".format(yname, xname, predict_x, predict_y, upredict_y))

        # Calcul de x(predict_y) pour estimer un point sur la droite
        print('Prédiction de {}({})'.format(xname, yname))
        predict_y = 36.50
        predict_x = predict_y/a - b/a
        upredict_x = np.sqrt((predict_y * uainv)**2 + ubinv**2)
        print("{}({} = {}) = {}({})".format(xname, yname, predict_y, predict_x, upredict_x))

        # Arrondi aux chiffres significatifs des coefficients
        decimal_a = -int(np.log10(ua) + (-1 if ua <= 1 else 0))
        ua_round = np.round(ua, decimal_a)
        a_round = np.round(a, decimal_a)
        decimal_b = -int(np.log10(ub) + (-1 if ub <= 1 else 0))
        ub_round = np.round(ub, decimal_b)
        b_round = np.round(b, decimal_b)

        # Affichage de la régression linéaire
        s = 'a = {} $\pm$ {} ; b = {} $\pm$ {} ; $\chi_r^2$ = {:.3f}'.format(a_round, ua_round, b_round, ub_round, chi2red)
        x_min, x_max = plt.xlim()
        x_space = np.linspace(x_min, x_max, 2)
        plt.plot(x_space, a*x_space + b, color=color, linewidth=1, label=s)
        plt.xlim(x_min, x_max)  # Un reset des limites est nécessaire

plot_data(data, data_live)
plot_data(data2)
plt.title('Ajustement: {} = a.{} + b ; {} = {}/a - b/a'.format(yname, xname, xname, yname))
plt.xlabel(xname + ' / ' + xunit)
plt.ylabel(yname + ' / ' + yunit)
plt.legend()

# Affichage
plt.show()