# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 14:16:27 2024

@author: Stéphane Pasquet
"""

import numpy as np
import matplotlib.pyplot as plt

# Données
annees = np.array([1850, 1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020, 2023])
population = np.array([1.25, 1.66, 1.75, 1.86, 2.07, 2.3, 2.5, 3, 3.7, 4.4, 5.3, 6.1, 6.9, 7.8, 8.0])

# Transformation des données : ln(y)
ln_population = np.log(population)


# Ajustement du modèle de régression linéaire sur les données transformées
coefficients_linear = np.polyfit(annees, ln_population, 1)
a_ln, b = coefficients_linear[0], coefficients_linear[1]
poly1d_fn = np.poly1d(coefficients_linear)

# Conversion des coefficients pour obtenir l'équation exponentielle
a = np.exp(b)
b = a_ln

# Fonction exponentielle ajustée
def exponential_fn(x):
    return a * np.exp(b * x)

# Création du graphique avec les ln(y_i)

plt.figure(figsize=(10, 6))
plt.plot(annees, ln_population, 'go-', label='ln de Population mondiale')
plt.plot(annees, poly1d_fn(annees), 'r--')
plt.text(1950, 2.01, f'Coefficient de corrélation: {round(np.corrcoef(annees,ln_population)[0,1], 3)}', fontsize=10, color='green')
plt.xlabel('Année')
plt.ylabel('Population (en milliards)')
plt.title('Logarithme de la population')
plt.grid(True)
plt.legend()
plt.show()

# Création du graphique avec la régression exponentielle
plt.figure(figsize=(10, 6))
plt.plot(annees, population, 'bo-', label='Population mondiale')
plt.plot(annees, exponential_fn(annees), 'r--', label=f'Régression exponentielle: y = {a:.4e} * e^({b:.4e}x)')
plt.text(1950, 7.2, f'Coefficient de corrélation: {round(np.corrcoef(exponential_fn(annees),population)[0,1], 3)}', fontsize=10, color='green')
plt.xlabel('Année')
plt.ylabel('Population (en milliards)')
plt.title('Évolution de la population mondiale avec régression exponentielle')
plt.grid(True)
plt.legend()
plt.show()

# Affichage des coefficients
print("Coefficients de la régression exponentielle: a =", a, ", b =", b)
