#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ce code permet de simuler le diagramme de Bode d'un filtre RLC (en prenant la tension aux bornes de R).
Ce code a été réalisé par Rullan Raphael. Me citer si uilisation. 
Je remercie Vincent Wieczny <3 pour le module Widgets qui permet de faire des sliders.
"""
#Importation des librairies

import numpy as np
import matplotlib.pyplot as plt
import widgets

#Définition des paramètres des Widgets

parameters = {'R' : widgets.IntSlider(value=470, description='résistance (en ohm)', min=1, max=10000),
              'L'  : widgets.FloatSlider(value = 0.04793, description='inductance (en Henry)', min = 0.00001, max =1),
              'C'  : widgets.FloatSlider(value = 1e-7, description='capacité (en Farad)', min = 1E-9, max = 1E-3)}

#Définition des fonctions
fig=plt.figure(figsize=(12,10))
plt.subplots_adjust(left=0.125,bottom=0.2,right=0.8,top=0.9,wspace=0.3,hspace=0.5)
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)

w = np.linspace(1,1000000,1000000)

def gain_pb(R,L,C,w):
    w_0 = 1/np.sqrt(L*C)
    Q = 1/(R*C*w_0)
    x = w/w_0
    return 20*np.log(1/(1+ (Q*(x - (1/x))**2)))

def passe_bande_P(x, R, L, C):
    omega_0 = 1/np.sqrt(L*C)
    Q = (1/R)*np.sqrt(L/C)
    z = x/omega_0
    return  - np.arctan(Q*(z-1/z))

def plot_data(R,L,C):
    lines['gain_pb'].set_data(w,gain_pb(R, L, C, w))
    ax1.set_ylim(np.min(gain_pb(R, L, C, w)),np.max(gain_pb(R, L, C, w))+10)
    ax2.set_ylim(np.min(passe_bande_P(w, R, L, C)),np.max(passe_bande_P(w, R, L, C)))
    texts1.set_text('Q = {:.2e}'.format((1/R)*np.sqrt(L/C)))
    texts2.set_text('w_0 = {:.2e}'.format(1/np.sqrt(L*C)))
    
    lines['phase_pb'].set_data(w,passe_bande_P(w, R, L, C))

lines = {}
lines['gain_pb'], = ax1.plot([], [],'r-',lw=2,label='Gain en décibel')
texts1=  ax1.text(0.4, 0.15,"Facteur de qualité, Q =" ,bbox=dict(facecolor='red', alpha=0.5), fontsize=10, transform=ax1.transAxes)
texts2=  ax1.text(0.6, 0.15,"pulsation propre (Hz) w_0=" ,bbox=dict(facecolor='red', alpha=0.5), fontsize=10, transform=ax1.transAxes)
ax1.set_xlim(1,np.max(w))
ax1.set_xscale('log')
ax1.set_xlabel('log(w)')
ax1.set_ylabel('20log(G)')
ax1.set_title('Courbe de gain en logarithme en fonction du logarithme de la pulsation pour un passe-bande')
ax1.legend()
lines['phase_pb'], = ax2.plot([], [],'r-',lw=2,label='Phase')
ax2.set_xscale('log')
ax2.set_xlabel('log(w)')
ax2.set_ylabel('phase')
ax2.set_xlim(1,np.max(w))

ax2.set_title('Courbe de phase en fonction du logarithme de la pulsation pour un passe-bande')

param_widgets = widgets.make_param_widgets(parameters, plot_data, slider_box=[0.35, 0.02, 0.35, 0.1])
choose_widget = widgets.make_choose_plot(lines, box=[0.85,0.2,0.15, 0.2])
reset_button = widgets.make_reset_button(param_widgets,box=[0.01, 0.01, 0.08, 0.05])


if __name__=='__main__':
    plt.show()


