# C filter, full-wave rectifier
# all voltages normalized by Vm
# all currents normalized by wCVm
# Vin=Vm cos(wt)

from pylab import *

#initialization
npoint = 720
i = arange(npoint)
deg = 360 * (i + 0.5) / npoint
wt = radians(deg)
phi = wt[0 : npoint / 2]
minp = cos(wt)
mx = abs(minp)
s = sign(minp)
wjc = - sin(wt) * s


close('all')
rc('text', usetex = True)
rc('font', family = 'serif')
rc('font', size = 12)
rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']

nf = 100 # number of frames, reduce if the simulation is too slow
Jout = empty(nf)
Pin = empty(nf)
Jinrms = empty(nf)
S = empty(nf)
PF = empty(nf)
Mout = empty(nf)
Pout = empty(nf)


figure(0, figsize = (4, 8))
degtick = (0, 60, 120, 180, 240, 300, 360)

Joutmax = 0.25

for k in range(nf):
    
    jout = (k - 0.5) / nf * Joutmax
    Jout[k] = jout
    
    beta = arcsin(jout)
    w1 = sqrt(1 - jout**2) - jout * (phi - beta)
    state1 = (phi > beta) & (w1 > mx[0 : npoint / 2])
    state = concatenate((state1, state1))
    w = concatenate((w1, w1))
    
    mout = w * float32(state) + mx * float32(~state)
    pout = jout * mout
    jc = wjc * float32(~state) - jout * float32(state)
    pc = mout * jc
    jd = jc + jout
    px = jd * mout
    jin = jd * s
    pin = minp * jin
    
    Pin[k] = mean(pin)
    Jinrms[k] = sqrt(mean(jin * jin))
    S[k] =Jinrms[k] / sqrt(2)
    PF[k] = Pin[k] / S[k]
    Mout[k] = mean(mout)
    Pout[k] = jout * Mout[k]
        
    clf()
    
    subplot(4, 1, 1)
    plot(deg, mout)
    ylabel(r'$m_{OUT}$')
    xlim(0, 360)
    xticks(degtick)
    ylim(- 1.2, 1.2)

    subplot(4, 1, 2)
    plot(deg, jd)
    plot(deg, jout * ones(len(deg)), 'r')
    ylabel(r'$j_D, \; J_{OUT}$')
    xlim(0, 360)
    xticks(degtick)
    ylim(- 6 * Joutmax, 6 * Joutmax)

    subplot(4, 1, 3)
    plot(deg, minp, 'b')
    plot(deg, - minp, '--b')
    plot(deg, mout, 'r')
    ylabel(r'$m_{IN}, \; - m_{IN}, \; m_{OUT}$')
    xlim(0, 360)
    xticks(degtick)
    ylim(- 1.2, 1.2)
    
    subplot(4, 1, 4)
    plot(deg, jin)
    xlabel(r'$\omega t [^\circ]$')
    ylabel(r'$j_{IN}$')
    xlim(0, 360)
    xticks(degtick)
    ylim(- 6 * Joutmax, 6 * Joutmax)
    
    savefig('cfilter{:d}.png'.format(k), bbox_inches = 'tight')
    

figure(1)
plot(Jout, Mout)
xlabel(r'$J_{OUT}$')
ylabel(r'$M_{OUT}$')
xlim(0, Joutmax)
ylim(0, 1)
savefig('Mout.png', bbox_inches = 'tight')

figure(2)
plot(Jout, Jinrms)
xlabel(r'$J_{OUT}$')
ylabel(r'$J_{IN RMS}$')
xlim(0, Joutmax)
ylim(0, 2 * Joutmax)
savefig('Jinrms.png', bbox_inches = 'tight')

figure(3)
plot(Jout, Pin, 'r')
plot(Jout, Pout, 'b')
xlabel(r'$J_{OUT}$')
ylabel(r'$P_{IN} \, [\text{red}], \; P_{OUT} \, [\text{blue}]$')
xlim(0, Joutmax)
ylim(0, Joutmax)
savefig('P.png', bbox_inches = 'tight')

figure(4)
plot(Jout,PF)
xlabel(r'$J_{OUT}$')
ylabel(r'$PF$')
xlim(0, Joutmax)
ylim(0, 1)
savefig('PF.png', bbox_inches = 'tight')

