import cmath as c # required to handle complex
import numpy as n
import pylab as p

# numerical values of the relevant quantities
RA1 = 6.8e2; CA1 = 4.7e-6
RA2 = 6.8e3; CA2 = 4.7e-7
RA3 = 6.8e4; CA3 = 4.7e-8
RB = 68; CB = 1.e-7
omegaB = 1/(RB*CB)

# array of frequencies
f = n.logspace(1,5,1000)

# convert freq in angular freq
def freq(ff):
    return ff*2*n.pi

# define the cutoff frequency A    
def omegaA(RRA,CCA):
    return 1/(RRA*CCA)

# define the transfer function (step by step!)
def deno(freq,CCB, CCA):
    return (1+1j*freq/omegaB+CCB/CCA)
    
def T1(freq,CCB,CCA):
    return ((1j*freq/omegaB)/deno(freq,CCB,CCA))

def T2(freq,CCB,CCA,omegaAA):
    return (1/(1+1j*(freq/omegaAA)-(CCB/CCA)*deno(freq,CCB,CCA)))

def TB(freq,CCB,CCA,omegaAA):
    return (T1(freq,CCB,CCA)*T2(freq,CCB,CCA,omegaAA))

# compute attenuation
def A(TT):
    return (n.sqrt(TT.real**2+TT.imag**2))

# compute dephasing
def deltafi(TT):
    return (n.arctan(TT.imag/TT.real)/n.pi)

# plot
p.subplot(2,1,1)
p.title('$f_{TA}$ = 49.8 Hz, $f_{TB}$ = 23.4 kHz',fontsize =14)
p.rc('font',size=14)
p.plot(f,A(TB(freq(f),CB,CA1,omegaA(RA1,CA1))),color='red')
p.plot(f,A(TB(freq(f),CB,CA2,omegaA(RA2,CA2))),color='green',linestyle='--')
p.plot(f,A(TB(freq(f),CB,CA3,omegaA(RA3,CA3))),color='blue',linestyle=':')
p.ylabel('$A(f)$', fontsize = 16)
p.grid()
p.yscale('log')
p.xscale('log')
p.legend([('$R_A=$ ' +str(RA1/1000)+' kohm, $C_A=$ ' +str(CA1/1e-6)+' $\mu$F'),('$R_A=$ ' +str(RA2/1000)+' kohm, $C_A=$ ' +str(int(CA2*1e8)/1e2)+' $\mu$F'),('$R_A=$ ' +str(RA3/1000)+' kohm, $C_A=$ ' +str(CA3/1e-6)+' $\mu$F')],fontsize=13,bbox_to_anchor=(1,.55)) 

p.subplot(2,1,2)
p.rc('font',size=14)
p.plot(f,deltafi(TB(freq(f),CB,CA1,omegaA(RA1,CA1))),color='red')
p.plot(f,deltafi(TB(freq(f),CB,CA2,omegaA(RA2,CA2))),color='green',linestyle='--')
p.plot(f,deltafi(TB(freq(f),CB,CA3,omegaA(RA3,CA3))),color='blue',linestyle=':')
p.ylabel('$\Delta \phi$  [$\pi$ rad]',fontsize=16) 
p.xlabel('$f$  [Hz]',fontsize = 16)
p.grid()
p.xscale('log')

p.savefig('D:/stash/dida14_15/lab2_14_15/complex/fig_intder.pdf')
p.show()
