Is There A Better Way To Simulate Pid Control In Python With Scipy's Solve_ivp()?
Solution 1:
Let's look at a more simple system, the ubiquitous spring with dampening
y'' + c*y' + k*y = u(t)
where u(t)
could represent the force exerted by an electro-magnet (which immediately suggests ways to make the system more complicated by introducing a more realistic relation of voltage and magnetic field).
Now in a PID controller we have the error to a reference output e = yr - y
and
u(t) = kD*e'(t) + kP*e(t) + kI*integral(e(t))
To treat this with an ODE solver we immediately see that the state needs to be extended with a new component E(t)
where E'(t)=e(t)
. The next difficulty is to implement the derivative of an expression that is not necessarily differentiable. This is achievable by avoiding to differentiate this expression at all by using a non-standard first-order implementation (where the standard would be to use [y,y',E]
as state).
Essentially, collect all derived expressions in the formula in their integrated form as
v(t)=y'(t)+c*y-kD*e(t).
Then going back to the derivative one gets the first order system
v'(t) = y''(t) + c*y'(t) - kD*e'(t)
= kP*e(t) + kI*E(t) - k*y(t)
y'(t) = v(t) - c*y(t) + kD*e(t)
E'(t) = e(t)
This now allows to implement the controlled system as ODE system without tricks involving a global memory or similar
defodePID(t,u,params):
c,k,kD,kP,kI = params
y,v,E = u
e = yr(t)-y
return [ v-c*y+kD*e, kP*e+kI*E-k*y, e ]
You should be able to use similar transformations of the first order system in your more complex model.
Post a Comment for "Is There A Better Way To Simulate Pid Control In Python With Scipy's Solve_ivp()?"