# -*- coding: utf-8 -*-
"""
Created on Sat Nov  8 22:24:55 2025

@author: AKourgli
"""

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt, hilbert

# --- Paramètres de base ---
fs = 100000       # Fréquence d'échantillonnage
t = np.arange(0, 0.02, 1/fs)  # 20 ms
fc = 2000         # Porteuse (Hz)
fm = 100          # Signal modulant (Hz)
kf = 2000         # Sensibilité fréquence (Hz/V)
Am = 1
Ac = 1

# --- Signal modulant ---
m_t = Am * np.sin(2 * np.pi * fm * t)

# --- Signal FM ---
int_m = np.cumsum(m_t) / fs
s_FM = Ac * np.cos(2 * np.pi * fc * t + 2 * np.pi * kf * int_m)


# --- Étape 1 : Dérivation du signal ---
#ds_dt = np.gradient(s_FM, 1/fs)

phi = np.unwrap(np.angle(hilbert(s_FM)))
ds_dt = np.gradient(phi, 1/fs) / (2*np.pi*kf)

# --- Étape 2 : Détection d'amplitude (enveloppe) ---
enveloppe = np.abs(ds_dt)

# --- Étape 3 : Filtrage passe-bas pour récupérer le signal modulant ---
def filtre_passe_bas(x, fc_cut, fs, order=4):
    b, a = butter(order, fc_cut/(fs/2), btype='low')
    return filtfilt(b, a, x)

m_rec = filtre_passe_bas(enveloppe, 500, fs)

# --- Normalisation pour comparaison ---
m_rec = m_rec - np.mean(m_rec)
m_rec = m_rec / np.max(np.abs(m_rec))

# --- Affichage ---
plt.figure(figsize=(10,8))

plt.subplot(4,1,1)
plt.plot(t, m_t)
plt.title("Signal modulant m(t)")
plt.xlabel("Temps (s)"); plt.ylabel("Amplitude")

plt.subplot(4,1,2)
plt.plot(t, s_FM)
plt.title("Signal FM reçu")
plt.xlabel("Temps (s)"); plt.ylabel("Amplitude")

plt.subplot(4,1,3)
plt.plot(t, ds_dt)
plt.title("Signal dérivé (étape du discriminateur à pente)")
plt.xlabel("Temps (s)"); plt.ylabel("Amplitude")

plt.subplot(4,1,4)
plt.plot(t, m_rec, label='Signal démodulé')
plt.plot(t, m_t, 'r--', label='m(t) original')
plt.title("Sortie du discriminateur de fréquence")
plt.xlabel("Temps (s)"); plt.ylabel("Amplitude")
plt.legend()

plt.tight_layout()
plt.show()
