In [3]:
import numpy as np
import sympy as sy
from sympy.utilities.codegen import codegen
import control.matlab as cm
import re
import matplotlib.pyplot as plt
from scipy import signal
sy.init_printing()
In [16]:
z = sy.symbols('z', real=False)
r1,r2,s0,s1,s2 = sy.symbols('r1,r2,s0,s1,s2', real=True)
hh,a = sy.symbols('h,a', real=True, positive=True)
# The plant
Bp = sy.poly(1./6*(z**2 + 4*z + 1), z)
Ap = sy.poly( sy.expand((z-1)**3), z)
# The desired characteristic polynomial
aa = 0.1
Ac = sy.poly( sy.expand((z-0.8)**3), z)
Ao = sy.poly(sy.expand((z-a)**2), z)
Acl = Ac*Ao
Rp = sy.poly(z**2+r1*z+r2, z)
Sp = sy.poly(s0*z**2 + s1*z + s2, z)
dioph=(Ap*Rp + Bp*Sp - Acl).all_coeffs()
print dioph
print Acl
print Ap*Rp
print Ac
print Ap*Rp
print Ap*Rp + Bp*Sp
In [17]:
sol = sy.solve(dioph, (r1,r2,s0,s1,s2))
print 'r_1 = %f' % sol[r1].subs(a, aa)
print 'r_2 = %f' % sol[r2].subs(a, aa)
print 's_0 = %f' % sol[s0].subs(a, aa)
print 's_1 = %f' % sol[s1].subs(a, aa)
print 's_1 = %f' % sol[s1].subs(a, aa)
In [18]:
# Check stability of the feedback controller
np.abs(np.roots([1, sol[r1].subs(a, aa), sol[r2].subs(a, aa) ]))
Out[18]:
In [19]:
t0 = Ac.evalf(subs={z:1})/Bp.evalf(subs={z:1,})
print 't_0 = %f' % t0
R = Rp.subs(sol)
S = Sp.subs(sol)
T = t0*Ao
In [ ]:
In [8]:
1.0/0.3125
Out[8]:
In [53]:
num = sy.list2numpy((Ap*R).all_coeffs(), dtype=np.float64)
den = sy.list2numpy((Ac*Ao).all_coeffs(), dtype=np.float64)
print num
print den
print type(num[0])
#Hd = cm.tf(num[:-1], den[:-1], -1)
Hd = cm.tf([1], [1, 0.5])
print Hd
ystep, t = cm.step(Hd, np.arange(30))
plt.figure()
plt.plot(t, ystep)
plt.show()
In [45]:
# Reorganize solution expression for matlab code generation
sol_expr = ('RST_DC_lab', [Bp.all_coeffs()[0], Bp.all_coeffs()[1],
Ap.all_coeffs()[1], Ap.all_coeffs()[2],
sol[r1], sol[s0], sol[s1], A2p.subs(z, 1)/Bp.subs(z,1), h,np.exp(h*po1) ])
In [46]:
# Export to matlab code
[(m_name, m_code)] = codegen(sol_expr, 'octave')
In [47]:
m_code = m_code.replace("out1", "b0").replace("out2", "b1").replace("out3", "a1").replace("out4", "a2")
m_code = m_code.replace("out5", "r1").replace("out6", "s0").replace("out7", "s1").replace("out8", "t0")
m_code = m_code.replace("out9", "h").replace("out10", "obsPole")
m_code = m_code.replace("function ", "% function ")
m_code = m_code.replace("end", "")
print m_code
with open("/home/kjartan/Dropbox/undervisning/tec/MR2007/labs/dc_rst_design.m", "w") as text_file:
text_file.write(m_code)
In [40]:
cm.step?
In [10]:
G = Km * cm.tf([1], [tau, 1, 0])
Gd = Km * cm.tf([tau*(hpt-1+np.exp(-hpt)), tau*(1-(1+hpt)*np.exp(-hpt))], [1, -(1+np.exp(-hpt)), np.exp(-hpt)], h)
Gd2 = cm.c2d(G, h)
print Gd
print Gd2
In [33]:
print A2p
print A2p.evalf(subs={z:1})
print Bp
print Bp.evalf(subs={z:1})
In [4]:
0.3/(5*np.sqrt(2))
Out[4]:
In [6]:
np.exp(-0.21)*np.sin(0.21)
Out[6]:
In [7]:
np.exp(0.03*(-14))
Out[7]:
In [42]:
0.746*41.8
Out[42]:
In [ ]: