-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathtransferfunction.jl
More file actions
522 lines (434 loc) · 18.8 KB
/
transferfunction.jl
File metadata and controls
522 lines (434 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
abstract type SisoTf end
include("polys.jl")
include("sisotf.jl")
include("sisozpk.jl")
include("sisogeneralized.jl")
#####################################################################
## Data Type Declarations ##
#####################################################################
type TransferFunction{S<:SisoTf} <: LTISystem
matrix::Matrix{S}
Ts::Float64
nu::Int
ny::Int
inputnames::Vector{String}
outputnames::Vector{String}
function TransferFunction{T}(matrix::Matrix{T}, Ts::Float64,
inputnames::Vector{String}, outputnames::Vector{String}) where T<:SisoTf
# Validate size of input and output names
ny, nu = size(matrix)
if size(inputnames, 1) != nu
error("Must have same number of inputnames as inputs")
elseif size(outputnames, 1) != ny
error("Must have same number of outputnames as outputs")
end
# Validate sampling time
if Ts < 0 && Ts != -1
error("Ts must be either a positive number, 0
(continuous system), or -1 (unspecified)")
end
return new{T}(matrix, Ts, nu, ny, inputnames, outputnames)
end
end
TransferFunction{T<:SisoTf}(matrix::Matrix{T}, args...) = TransferFunction{T}(matrix, args...)
+{T<:Real}(a::TransferFunction, b::AbstractVecOrMat{T}) = +(promote(a,b)...)
Base.promote_rule{S<:SisoTf,T<:Real}(::Type{TransferFunction{S}}, ::Type{T}) = TransferFunction{S}
Base.promote_rule{S<:SisoTf,T<:Real}(::Type{TransferFunction{S}}, ::Union{Type{Array{T,2}},Type{Array{T,1}}}) = TransferFunction{S}
Base.convert{T<:Real}(::Type{TransferFunction}, b::T) = tf([b])
Base.convert{T<:Real}(::Type{TransferFunction{SisoRational}}, b::T) = tf(b)
Base.convert{T<:Real}(::Type{TransferFunction{SisoZpk}}, b::T) = zpk(b)
Base.convert{T<:Real}(::Type{TransferFunction{SisoGeneralized}}, b::T) = tfg(b)
Base.convert(::Type{TransferFunction{SisoZpk}}, s::TransferFunction) = zpk(s)
Base.convert(::Type{TransferFunction{SisoRational}}, s::TransferFunction) = tf(s)
Base.convert(::Type{TransferFunction{SisoGeneralized}}, s::TransferFunction) = tfg(s)
Base.promote_rule(::Type{TransferFunction{SisoRational}}, ::Type{TransferFunction{SisoZpk}}) = TransferFunction{SisoZpk}
Base.promote_rule{T<:SisoTf}(::Type{TransferFunction{T}}, ::Type{TransferFunction{SisoGeneralized}}) = TransferFunction{SisoGeneralized}
Base.promote_rule(::Type{SisoRational}, ::Type{SisoZpk}) = SisoZpk
Base.promote_rule{T<:SisoTf}(::Type{T}, ::Type{SisoGeneralized}) = SisoGeneralized
function Base.convert{T<:Real}(::Type{TransferFunction}, b::VecOrMat{T})
r = Array{TransferFunction,2}(size(b,2),1)
for j=1:size(b,2)
r[j] = vcat(map(k->convert(TransferFunction,k),b[:,j])...)
end
hcat(r...)
end
function Base.convert(::Type{SisoZpk}, sys::SisoRational)
if length(sys.num) == 0
return SisoZpk([],[],0)
elseif all(sys.den == zero(sys.den))
error("Zero denominator, this should not be possible")
else
return SisoZpk(roots(sys.num),roots(sys.den),sys.num[1]/sys.den[1])
end
end
function Base.convert(::Type{SisoRational}, sys::SisoZpk)
num = prod(zp2polys(sys.z))*sys.k
den = prod(zp2polys(sys.p))
return SisoRational(num, den)
end
Base.convert(::Type{SisoGeneralized}, sys::SisoRational) = SisoGeneralized(sprint(print_compact, sys))
Base.convert(::Type{SisoGeneralized}, sys::SisoZpk) = convert(SisoGeneralized, convert(SisoRational, sys))
Base.convert(::Type{SisoRational}, sys::SisoGeneralized) = SisoRational(sys.expr)
Base.convert(::Type{SisoZpk}, sys::SisoGeneralized) = convert(SisoZpk, SisoRational(sys.expr))
#Just default SisoTf to SisoRational
SisoTf(args...) = SisoRational(args...)
Base.convert(::Type{ControlSystems.SisoTf}, b::Real) = Base.convert(ControlSystems.SisoRational, b)
Base.zero(::Type{SisoTf}) = zero(SisoRational)
Base.zero(::SisoTf) = zero(SisoRational)
tzero(sys::SisoTf) = error("tzero is not implemented for type $(typeof(sys))")
#####################################################################
## SisoTf Operations ##
#####################################################################
#These make sure that the matrix operation below works as expected
#Base.convert(::Type{SisoTf}, b::Real) = Base.convert(SisoRational, b)
*{T<:SisoTf}(a::Array{T}, b::Real) = map(x->x*b,a)
*{T<:SisoTf}(b::Real, a::Array{T}) = map(x->x*b,a)
/{T<:SisoTf}(a::Array{T}, b::Real) = map(x->x/b,a)
+{T<:SisoTf}(a::Array{T}, b::Real) = map(x->x+b,a)
+{T<:SisoTf}(b::Real, a::Array{T}) = map(x->x+b,a)
-{T<:SisoTf}(a::Array{T}, b::Real) = map(x->x-b,a)
-{T<:SisoTf}(b::Real, a::Array{T}) = map(x->b-x,a)
-{T<:SisoTf}(a::Array{T}) = map(x-> -x,a)
#Operations with different types of Siso functions
*(a::SisoTf, b::SisoTf) = *(promote(a,b)...)
+(a::SisoTf, b::SisoTf) = +(promote(a,b)...)
-(a::SisoTf, b::SisoTf) = -(promote(a,b)...)
#.*(a::SisoTf, b::SisoTf) = .*(promote(a,b)...)
#.+(a::SisoTf, b::SisoTf) = .+(promote(a,b)...)
#.-(a::SisoTf, b::SisoTf) = .+(promote(a,b)...)
==(a::SisoTf, b::SisoTf) = ==(promote(a,b)...)
!=(a::SisoTf, b::SisoTf) = !(a==b)
isapprox(a::SisoTf, b::SisoTf; kwargs...) = isapprox(promote(a,b)...; kwargs...)
# Promote_op types
Base.promote_op{T<:SisoTf}(::Any, ::Type{T}, ::Type{T}) = T
#####################################################################
## Constructor Functions ##
#####################################################################
@doc """ `sys = tf(num, den, Ts=0; kwargs...), sys = tf(gain, Ts=0; kwargs...)`
Create transfer function as a fraction of polynomials:
`sys = numerator/denominator`
`num`: the coefficients of the numerator polynomial. Either scalar or vector to create SISO systems
or an array of vectors to create MIMO system.
`den`: the coefficients of the denominator polynomial. Either vector to create SISO systems
or an array of vectors to create MIMO system.
`Ts`: Sample time or `0` for continuous system.
`kwargs`: `inputnames`, `outputnames`: Arrays of strings representing the inputs and outputs.
Other uses:
`tf(sys)`: Convert `sys` to `tf` form.
`tf("s")`, `tf("z")`: Create the continous transferfunction `s`.""" ->
function tf{T<:Vector, S<:Vector}(num::VecOrMat{T}, den::VecOrMat{S}, Ts::Real=0; kwargs...)
# Validate input and output dimensions match
ny, nu = size(num, 1, 2)
if (ny, nu) != size(den, 1, 2)
error("num and den dimensions must match")
end
matrix = Array{SisoRational}(ny, nu)
for o=1:ny
for i=1:nu
matrix[o, i] = SisoRational(num[o, i], den[o, i])
end
end
kvs = Dict(kwargs)
inputnames = validate_names(kvs, :inputnames, nu)
outputnames = validate_names(kvs, :outputnames, ny)
return TransferFunction(matrix, Float64(Ts), inputnames, outputnames)
end
@doc """ `zpk(gain, Ts=0; kwargs...), zpk(num, den, k, Ts=0; kwargs...), zpk(sys)`
Create transfer function on zero pole gain form. The numerator and denominator are represented by their poles and zeros.
`sys = k*numerator/denominator`
`num`: the roots of the numerator polynomial. Either scalar or vector to create SISO systems
or an array of vectors to create MIMO system.
`den`: the roots of the denominator polynomial. Either vector to create SISO systems
or an array of vectors to create MIMO system.
`k`: The gain of the system. Obs, this is not the same as `dcgain`.
`Ts`: Sample time or `0` for continuous system.
`kwargs`: `inputnames`, `outputnames`: Arrays of strings representing the inputs and outputs.
Other uses:
`tf(sys)`: Convert `sys` to `tf` form.
`tf("s")`: Create the transferfunction `s`.""" ->
function zpk{T<:Vector,S<:Vector}(z::VecOrMat{T}, p::VecOrMat{S}, k::VecOrMat, Ts::Real=0; kwargs...)
# Validate input and output dimensions match
ny, nu = size(z, 1, 2)
if (ny, nu) != size(p, 1, 2) || (ny, nu) != size(k, 1, 2)
error("s, p, and k kdimensions must match")
end
matrix = Array{SisoZpk}(ny, nu)
for o=1:ny
for i=1:nu
matrix[o, i] = SisoZpk(z[o, i], p[o, i], k[o, i])
end
end
kvs = Dict(kwargs)
inputnames = validate_names(kvs, :inputnames, nu)
outputnames = validate_names(kvs, :outputnames, ny)
return TransferFunction(matrix, Float64(Ts), inputnames, outputnames)
end
function zpk(tf::TransferFunction)
oldmat = tf.matrix
matrix = Array{SisoZpk}(tf.ny, tf.nu)
for i in eachindex(oldmat)
matrix[i] = convert(SisoZpk, oldmat[i])
end
return TransferFunction(matrix, tf.Ts, copy(tf.inputnames), copy(tf.outputnames))
end
function tf(tf::TransferFunction)
oldmat = tf.matrix
matrix = Array{SisoRational}(tf.ny, tf.nu)
for i in eachindex(oldmat)
matrix[i] = convert(SisoRational, oldmat[i])
end
return TransferFunction(matrix, tf.Ts, copy(tf.inputnames), copy(tf.outputnames))
end
@doc """ `sys = tfg(tf::LTISystem), `tfg(s::AbstractString)`, `tfg(exp::Expr)`, `tfg(::Array)`
Create generalized transfer function represented by an expression. The variable has to be `s`.
Example: `tfg("1/exp(-sqrt(s))")`, `tfg(["1/exp(-sqrt(s))"), "1/(s+1)])`, `tfg(:(s+1))`
Other uses:
`tfg(sys)`: Convert `sys` to `tfg` form.
""" ->
function tfg(tf::TransferFunction)
oldmat = tf.matrix
matrix = Array{SisoGeneralized}(tf.ny, tf.nu)
for i in eachindex(oldmat)
matrix[i] = convert(SisoGeneralized, oldmat[i])
end
return TransferFunction(matrix, tf.Ts, copy(tf.inputnames), copy(tf.outputnames))
end
zpk(sys::TransferFunction{SisoGeneralized}) = zpk(tf(sys))
tf(num::Vector, den::Vector, Ts::Real=0; kwargs...) =
tf(reshape(Vector[num], 1, 1), reshape(Vector[den], 1, 1), Ts; kwargs...)
tf(num::Real, den::Vector, Ts::Real=0; kwargs...) = tf([num], den, Ts; kwargs...)
zpk(z::Vector, p::Vector, k::Real, Ts::Real=0; kwargs...) =
zpk(reshape(Vector[z], 1, 1), reshape(Vector[p], 1, 1), reshape([k],1,1), Ts; kwargs...)
# Function for creation of static gain
function tf(gain::Array, Ts::Real=0; kwargs...)
ny, nu = size(gain, 1, 2)
matrix = Array{SisoRational}(ny, nu)
for i in eachindex(gain)
matrix[i] = SisoRational([gain[i]], [1])
end
kvs = Dict(kwargs)
inputnames = validate_names(kvs, :inputnames, nu)
outputnames = validate_names(kvs, :outputnames, ny)
return TransferFunction(matrix, Float64(Ts), inputnames, outputnames)
end
function zpk(gain::Array, Ts::Real=0; kwargs...)
ny, nu = size(gain, 1, 2)
matrix = Array{SisoZpk}(ny, nu)
for o=1:ny
for i=1:nu
matrix[o, i] = SisoZpk([],[], gain[o, i])
end
end
kvs = Dict(kwargs)
inputnames = validate_names(kvs, :inputnames, nu)
outputnames = validate_names(kvs, :outputnames, ny)
return TransferFunction(matrix, Float64(Ts), inputnames, outputnames)
end
tf(gain::Real, Ts::Real=0; kwargs...) = tf([gain], Ts; kwargs...)
zpk(k::Real, Ts::Real=0; kwargs...) = zpk([], [], k, Ts; kwargs...)
# Function for creation of 's' or 'z' var
function tf(var::AbstractString)
var != "s" && error("var must be 's' for continuous time tf.")
return tf([1, 0], [1])
end
function tf(var::AbstractString, Ts::Real)
var != "z" && error("var must be 'z' for discrete time tf.")
Ts == 0 && error("Ts must not be 0 for discrete time tf.")
return tf([1, 0], [1], Ts)
end
zpk(var::AbstractString) = zpk(tf(var))
zpk(var::AbstractString, Ts::Real) = zpk(tf(var, Ts))
function tfg(systems::Array, Ts::Real=0; kwargs...)
ny, nu = size(systems, 1, 2)
matrix = Array{SisoGeneralized}(ny, nu)
for o=1:ny
for i=1:nu
matrix[o, i] = SisoGeneralized(systems[o, i])
end
end
kvs = Dict(kwargs)
inputnames = validate_names(kvs, :inputnames, nu)
outputnames = validate_names(kvs, :outputnames, ny)
return TransferFunction(matrix, Float64(Ts), inputnames, outputnames)
end
tfg(var::Union{AbstractString,ExprLike}, Ts=0; kwargs...) = tfg([var], Ts; kwargs...)
#####################################################################
## Misc. Functions ##
#####################################################################
## INDEXING ##
Base.ndims(::TransferFunction) = 2
Base.size(t::TransferFunction) = (t.ny, t.nu)
Base.size(t::TransferFunction, d) = d <= 2 ? size(t)[d] : 1
function Base.getindex(t::TransferFunction, inds...)
if size(inds, 1) != 2
error("Must specify 2 indices to index TransferFunction model")
end
rows, cols = ControlSystems.index2range(inds...)
T = eltype(t.matrix)
mat = Array{T}(length(rows), length(cols))
mat[:, :] = t.matrix[rows, cols]
innames = String[t.inputnames[i] for i in cols]
outnames = String[t.outputnames[i] for i in rows]
return TransferFunction(mat, t.Ts, innames, outnames)
end
function Base.copy(t::TransferFunction)
matrix = copy(t.matrix)
inputnames = copy(t.inputnames)
outputnames = copy(t.outputnames)
return TransferFunction(matrix, t.Ts, inputnames, outputnames)
end
@doc """`tf = minreal(tf::TransferFunction, eps=sqrt(eps()))`
Create a minimial representation of each transfer function in `tf` by cancelling poles and zeros """ ->
function minreal(t::TransferFunction, eps::Real=sqrt(eps()))
matrix = similar(t.matrix)
for i = eachindex(t.matrix)
matrix[i] = minreal(t.matrix[i], eps)
end
return TransferFunction(matrix, t.Ts, copy(t.inputnames), copy(t.outputnames))
end
#####################################################################
## Math Operators ##
#####################################################################
## EQUALITY ##
function ==(t1::TransferFunction, t2::TransferFunction)
fields = [:Ts, :ny, :nu, :inputnames, :outputnames, :matrix]
for field in fields
if getfield(t1, field) != getfield(t2, field)
return false
end
end
return true
end
## Approximate ##
function isapprox(t1::TransferFunction, t2::TransferFunction; kwargs...)
t1, t2 = promote(t1, t2)
fieldsApprox = [:Ts, :ny, :nu, :matrix]
fieldsEqual = [:inputnames, :outputnames]
for field in fieldsApprox
if !(isapprox(getfield(t1, field), getfield(t2, field); kwargs...))
return false
end
end
for field in fieldsEqual
if getfield(t1, field) != getfield(t2, field)
return false
end
end
return true
end
function isapprox{T<:SisoTf, S<:SisoTf}(t1::Array{T}, t2::Array{S}; kwargs...)
reduce(&, [isapprox(t1[i], t2[i]; kwargs...) for i in eachindex(t1)])
end
## ADDITION ##
function +(t1::TransferFunction, t2::TransferFunction)
if size(t1) != size(t2)
error("Systems have different shapes.")
elseif t1.Ts != t2.Ts
error("Sampling time mismatch")
end
# Naming strategy: If only one sys is named, use that. If the names are the
# same, use them. If the names conflict, then they are ignored, and the
# default "" is used.
if all(t1.inputnames .== "")
inputnames = t2.inputnames
elseif all(t2.inputnames .== "") || (t1.inputnames == t2.inputnames)
inputnames = t1.inputnames
else
inputnames = fill(String(""),t1.ny)
end
if all(t1.outputnames .== "")
outputnames = t2.outputnames
elseif all(t2.outputnames .== "") || (t1.outputnames == t2.outputnames)
outputnames = t1.outputnames
else
outputnames = fill(String(""),t1.nu)
end
t1, t2 = promote(t1, t2)
matrix = t1.matrix + t2.matrix
return TransferFunction(matrix, t1.Ts, inputnames, outputnames)
end
+(t::TransferFunction, n::Real) = TransferFunction(t.matrix + n, t.Ts,
t.inputnames, t.outputnames)
+(n::Real, t::TransferFunction) = +(t, n)
## SUBTRACTION ##
-(n::Real, t::TransferFunction) = TransferFunction(n - t.matrix, t.Ts,
t.inputnames, t.outputnames)
-(t1::TransferFunction, t2::TransferFunction) = +(t1, -t2)
-(t::TransferFunction, n::Real) = +(t, -n)
## NEGATION ##
-(t::TransferFunction) = TransferFunction(-t.matrix, t.Ts, t.inputnames,
t.outputnames)
## MULTIPLICATION ##
function *(t1::TransferFunction, t2::TransferFunction)
# Note: t1*t2 = y <- t1 <- t2 <- u
if t1.nu != t2.ny
error("t1*t2: t1 must have same number of inputs as t2 has outputs")
elseif t1.Ts != t2.Ts
error("Sampling time mismatch")
end
matrix = t1.matrix*t2.matrix
return TransferFunction(matrix, t1.Ts, t2.inputnames, t1.outputnames)
end
*(t::TransferFunction, n::Real) = TransferFunction(n*t.matrix, t.Ts,
t.inputnames, t.outputnames)
*(n::Real, t::TransferFunction) = *(t, n)
## DIVISION ##
function /(n::Real, t::TransferFunction)
if issiso(t)
matrix = reshape([n/t.matrix[1,1]], 1, 1)
else
error("MIMO TransferFunction inversion isn't implemented yet")
end
return TransferFunction(matrix, t.Ts, t.outputnames, t.inputnames)
end
/(t::TransferFunction, n::Real) = t*(1/n)
/(t1::TransferFunction, t2::TransferFunction) = t1*(1/t2)
#####################################################################
## Display Functions ##
#####################################################################
@doc """`print(io::IO, t::TransferFunction, precision::Int=-1)`
Print a string representation of the transfer function:
`io`: the `IO` stream to print to
`t`: the transfer function
`precision`: the precision to round each number to (default is 5)
Other uses:
`print(t::TransferFunction, precision::Int=-1)`: prints to `STDOUT`""" ->
Base.print(io::IO, t::TransferFunction, precision::Int=-1) = show(io, t, precision)
Base.print(t::TransferFunction, precision::Int=-1) = show(t, precision)
@doc """`show(io::IO, t::TransferFunction, precision::Int=-1)`
Print a string representation of the transfer function:
`io`: the `IO` stream to print to
`t`: the transfer function
`precision`: the precision to round each number to (default is 5)
Other uses:
`show(t::TransferFunction, precision::Int=-1)`: prints to `STDOUT`""" ->
function Base.show(io::IO, t::TransferFunction, precision::Int=-1)
# Compose the name vectors
inputs = format_names(t.inputnames, "Input ", "?")
outputs = format_names(t.outputnames, "Output ", "?")
println(io, "TransferFunction:")
tftype = iscontinuous(t) ? :s : :z
for i=1:t.nu
for o=1:t.ny
if !issiso(t)
println(io, inputs[i], " to ", outputs[o])
end
print_siso(io, t.matrix[o, i], tftype, precision)
if !(i == t.nu && o == t.ny)
print(io, "\n")
end
end
end
if iscontinuous(t)
print(io, "\nContinuous-time transfer function model")
else
print(io, "\nSample Time: ")
if t.Ts > 0
print(io, t.Ts, " (seconds)")
elseif t.Ts == -1
print(io, "unspecified")
end
print(io, "\nDiscrete-time transfer function model")
end
end
Base.show(t::TransferFunction, precision::Int=-1) = show(STDOUT, t, precision)