"""
Simulation du moteur
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as scint

## Définition des constantes du moteur

R, L = 10, 0.0022 ## Ohm, H
Kc = 2.1 ## N.m/A
Ke = Kc ## V.s/rad
fv, J = 0.04, 7E-3 ## Nm.s/rad, kg.m²

u_max = 12 ## V
Cr0 = 0.2 ## N.m

## Points expérimentaux

data = np.loadtxt('./CI-SLCI-4-Mot-DeltaBot/CI-SLCI-4 Commande en tension 12V.csv',
                  delimiter = ',', skiprows = 1)

fic = open('./CI-SLCI-4-Mot-DeltaBot/CI-SLCI-4 Commande en tension 12V.csv',
           'r', encoding = 'utf8')
tout = fic.readlines()
fic.close()

titres = tout[0].rstrip().split(',')

Texp = data[:, 0]
Iexp = data[:, 2]
Wexp = data[:,3]
plt.figure('intensité')
plt.plot(Texp, Iexp)
plt.figure('Vitesse de rotation')
plt.plot(Texp, Wexp)
plt.show(block = False)


## Données liées à la simulation

nbp = 200
t0, tf = 0, 10 ##Texp[0], Texp[-1] ## s, s

i0 = 0 ## A
wm0 = 0 ## rad/s

Y0 = np.array([i0, wm0])

td = 0 ## s
tc = tf # td + (tf-td)/2 ## s

def u_m(t):
    if t < td or t > tc:
        return 0
    return u_max

def c_r(t):
    return 0

## Simulation

def F_mot(Y, t):
    f0 = (u_m(t)-Ke*Y[1]-R*Y[0]) / L
    f1 = (Kc*Y[0]-c_r(t)-fv*Y[1]) / J
    return np.array([f0, f1])


T = np.linspace(t0, tf, nbp)
sim = scint.odeint(F_mot, Y0, T)
I = sim[:, 0] ## Intensité
W = sim[:, 1] ## vitesse de rotation

## Présentation des résultats simulés

plt.figure('intensité')
plt.title(r'$i(t)$ (A)')
plt.plot(T, I)

plt.figure('Vitesse de rotation')
plt.title(r'$\omega_m(t)$ (rad/s)')
plt.plot(T, W)






