Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 98 additions & 25 deletions docs/src/examples/delayest.md

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/ControlSystemIdentification.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,16 @@ export kautz, laguerre, laguerre_oo, laguerre_id, adhocbasis, sum_basis, basis_r

export autocorplot, crosscorplot, modelfit, residualplot

export find_delay, DelaySweep

export prbs, chirp, multisine, step_signal

include("utils.jl")
include("types.jl")
include("frd.jl")
include("pem.jl")
include("arx.jl")
include("delay.jl")
include("subspace.jl")
include("subspace2.jl")
include("spectrogram.jl")
Expand Down
123 changes: 123 additions & 0 deletions src/delay.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""
DelaySweep

Result of [`find_delay`](@ref). Fields:
- `delay`: the delay (in samples, using the convention of the `inputdelay` keyword of [`arx`](@ref)) with the smallest loss.
- `delays`: the candidate delays.
- `loss`: the normalized RMS validation error for each candidate delay.
- `Ts`: the sample time of the data.

A `DelaySweep` can be plotted using `plot(sweep)`.
"""
struct DelaySweep
delay::Int
delays::Vector{Int}
loss::Vector{Float64}
Ts::Float64
end

function Base.show(io::IO, ::MIME"text/plain", s::DelaySweep)
print(io, "DelaySweep: best inputdelay = $(s.delay) samples")
s.Ts > 0 && print(io, " ($(s.delay * s.Ts) s)")
i = findfirst(==(s.delay), s.delays)
print(io, ", normalized RMS error $(s.loss[i])")
end

"""
find_delay(d::InputOutputData, na, nb, delays = 1:20; dval = d, metric = :simulation, skip, kwargs...)

Estimate the input delay of a single-input single-output system by fitting one ARX model [`arx`](@ref)`(d, na, nb; inputdelay = k, kwargs...)` for each candidate delay `k` in `delays` and comparing the models on validation data.

The delay convention is the same as for the `inputdelay` keyword of [`arx`](@ref): `k = 1` is the default and corresponds to a system without any delay beyond the one sample that is required for causality of a strictly proper discrete-time system, and `k = 0` corresponds to a direct term. A strictly proper plant with a relative degree of one and a pure delay of `n` samples thus has `k = n + 1`, while in general `k = n + r`, where `r` is the relative degree of the discrete-time dynamics without the delay.

The orders `na` and `nb` determine the dynamics that can be represented by each candidate model. `nb` should not be much larger than the number of numerator coefficients of the delay-free system, since a large `nb` allows the estimator to compensate a too short delay with leading coefficients of the B polynomial, which flattens the loss as a function of the delay. `na` should be at least the order of the delay-free system, and somewhat larger if the data contains measurement noise, since [`arx`](@ref) is biased by output noise and a too small `na` results in a biased delay estimate. The estimate is therefore most accurate for data with a high signal-to-noise ratio, and should otherwise be considered approximate, in which case the estimated delay can be refined by comparing other model structures using the same validation data.

# Arguments:
- `d`: Identification data used for estimation.
- `na`, `nb`: Orders of the A and B polynomials.
- `delays`: Candidate delays in samples.
- `dval`: Validation data. It is recommended to provide data that was not used for estimation. Defaults to `d`.
- `metric`: Either `:simulation` (default) or `:prediction`. The simulation error is considerably more sensitive to a wrong delay than the one-step prediction error, but requires that `dval` starts from rest (or that `skip` is chosen to exclude the transient). The prediction error is computed from the measured outputs and is not affected by the initial state.
- `skip`: The number of initial samples of `dval` that are excluded from the loss. By default `0` for `:simulation` and the largest regressor length among the candidates for `:prediction`, such that all candidates are compared on the same samples. For `:prediction`, a smaller value is rejected.
- `kwargs`: Additional keyword arguments are passed to [`arx`](@ref), e.g., `λ` for regularization.

# Returns
A [`DelaySweep`](@ref) with the fields `delay`, `delays`, `loss`, `Ts`. Plot the loss as a function of the delay using `plot(sweep)`. Loss values larger than the keyword argument `lossmax` (default `10`) are clipped in the plot, which prevents unstable candidate models from dominating the scale.

The estimate is limited to integer multiples of the sample time. Candidate models for which the simulation diverges, or that are otherwise non-finite, are never selected.

# Example
```julia
using ControlSystemIdentification, ControlSystemsBase, Plots
Ts = 0.1
P = c2d(tf(1, [1, 0.5, 1]) * delay(2.0), Ts)
u = randn(1, 400)
d = iddata(lsim(P, u))
sweep = find_delay(d, 2, 2, 0:40)
sweep.delay # 21 samples, i.e., 20 samples of pure delay plus the one sample required for causality
plot(sweep)
```
"""
function find_delay(
d::InputOutputData,
na::Integer,
nb::Integer,
delays = 1:20;
dval::InputOutputData = d,
metric::Symbol = :simulation,
skip::Integer = -1,
kwargs...,
)
d.ny == 1 && d.nu == 1 || throw(ArgumentError("find_delay only supports single-input single-output data."))
dval.ny == 1 && dval.nu == 1 || throw(ArgumentError("The validation data must be single-input single-output."))
metric in (:simulation, :prediction) || throw(ArgumentError("metric must be :simulation or :prediction"))
delays = collect(Int, delays)
isempty(delays) && throw(ArgumentError("delays must not be empty"))
d.Ts === nothing || dval.Ts === nothing || d.Ts == dval.Ts ||
throw(ArgumentError("The sample times of the estimation data ($(d.Ts)) and the validation data ($(dval.Ts)) differ."))
# Number of initial samples for which the one-step prediction of every candidate is unavailable
skip_min = metric === :prediction ? max(na, nb + maximum(delays) - 1) : 0
if skip < 0
skip = skip_min
elseif skip < skip_min
throw(ArgumentError("skip must be at least $skip_min for metric = :prediction, since the prediction is unavailable for the first samples of the candidate models with the longest regressors."))
end
skip < length(dval) || throw(ArgumentError("skip must be smaller than the length of the validation data"))
y = vec(output(dval))
yr = y[skip+1:end]
scale = rms(yr .- mean(yr))
scale > 0 || throw(ArgumentError("The validation output is constant."))
loss = map(delays) do k
G = arx(d, na, nb; inputdelay = k, kwargs...)
yh = if metric === :prediction
vec(predict(G, dval))
else
Gs = ss(G)
vec(simulate(Gs, dval, zeros(Gs.nx)))
end
e = (y .- yh)[skip+1:end]
sqrt(mean(abs2, e)) / scale
end
any(isfinite, loss) || error("No candidate delay resulted in a finite loss.")
_, i = findmin(l -> isfinite(l) ? l : Inf, loss)
DelaySweep(delays[i], delays, loss, d.Ts === nothing ? 0.0 : Float64(d.Ts))
end

@recipe function plot_delaysweep(s::DelaySweep; lossmax = 10)
xguide --> "Input delay [samples]"
yguide --> "Normalized RMS error"
yscale --> :log10
title --> "Delay sweep"
label --> ""
@series begin
seriestype := :scatter
s.delays, clamp.(s.loss, eps(), lossmax)
end
@series begin
seriestype := :vline
linestyle := :dash
seriescolor := :black
label := "Best delay"
[s.delay]
end
end
7 changes: 5 additions & 2 deletions src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,14 @@ modelfit(y::T, yh::T) where {T<:AbstractVector} =

Akaike's Information Criterion (AIC) for model order selection.

`e` is the prediction errors and `d` is the number of parameters estimated.
`e` is the prediction errors and `d` is the number of parameters estimated. The criterion is normalized by the number of samples `N = length(e)`, i.e., it is computed as `log(sse(e) / N) + 2d / N`.

See also [`fpe`](@ref).
"""
aic(x::AbstractVector, d) = log(sse(x)) .+ 2d / size(x, 2)
function aic(x::AbstractVector, d)
N = length(x)
log(sse(x) / N) + 2d / N
end

"See [`modelfit`](@ref)"
const nrmse = modelfit
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@ end
include("test_arx.jl")
end

@testset "find_delay" begin
@info "Testing find_delay"
include("test_delay.jl")
end

@testset "ar" begin
@info "Testing ar"
include("test_ar.jl")
Expand Down
48 changes: 48 additions & 0 deletions test/test_delay.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using ControlSystemIdentification, ControlSystemsBase, Plots, Random, Statistics

Random.seed!(1)
Ts = 0.1
τ_samples = 20
P = c2d(tf(1, [1, 0.5, 1]) * delay(τ_samples * Ts), Ts)
u = randn(1, 400)
y = lsim(P, u)[1]
d = iddata(y, u, Ts)

# The input delay convention of `arx` is that the default `inputdelay = 1` is a delay-free strictly proper system
for metric in (:simulation, :prediction)
sweep = find_delay(d, 2, 2, 0:40; metric)
@test sweep.delay == τ_samples + 1
@test sweep.delays == 0:40
@test length(sweep.loss) == 41
@test sweep.loss[sweep.delay+1] < 1e-6
@test sweep.Ts == Ts
end

# separate validation data and noise
mk(N) = (u = randn(1, N); iddata(lsim(P, u)[1] .+ 0.01randn(1, N), u, Ts))
dt, dv = mk(600), mk(600)
sweep = find_delay(dt, 4, 4, 0:40; dval = dv)
@test abs(sweep.delay - (τ_samples + 1)) <= 2

# keyword arguments are forwarded to arx
sweep = find_delay(d, 2, 2, 15:25; λ = 1e-10)
@test sweep.delay == τ_samples + 1
k = τ_samples + 1
loss(λ) = find_delay(d, 2, 2, k:k; λ).loss[]
G = arx(d, 2, 2; inputdelay = k, λ = 100)
Gs = ss(G)
yh = vec(simulate(Gs, d, zeros(Gs.nx)))
@test loss(100) ≈ sqrt(mean(abs2, vec(d.y) .- yh)) / std(vec(d.y), corrected = false)
@test loss(100) > 10loss(0)

# plotting and display
plot(sweep)
show(IOBuffer(), MIME("text/plain"), sweep)

# error handling
@test_throws ArgumentError find_delay(d, 2, 2, 0:40; metric = :prediction, skip = 0)
@test_throws ArgumentError find_delay(d, 2, 2, 0:5; dval = iddata(y, u, 2Ts))
@test_throws ErrorException find_delay(d, 2, 2, 1:3; dval = iddata(y, fill(Inf, 1, 400), Ts))
@test_throws ArgumentError find_delay(d, 2, 2, 0:40; metric = :foo)
@test_throws ArgumentError find_delay(d, 2, 2, 1:0)
@test_throws ArgumentError find_delay(iddata(randn(2, 50), randn(1, 50), 1), 2, 2)
7 changes: 6 additions & 1 deletion test/test_utils.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Test
using ControlSystemIdentification
using ControlSystemIdentification: time1, time2, rms, sse, mse, fpe, modelfit
using ControlSystemIdentification: time1, time2, rms, sse, mse, fpe, aic, modelfit
using Statistics
v = zeros(2)
M = zeros(2, 4)
Expand Down Expand Up @@ -29,6 +29,11 @@ y = randn(1, 3)
@test fpe(zeros(5), 3) == 0
@test fpe(zeros(2, 5), 3) == 0

# aic of a vector is normalized by the number of samples, so that the penalty is 2d/N
e = [1.0, -1.0, 2.0, -2.0]
@test aic(e, 3) ≈ log(sum(abs2, e) / 4) + 2 * 3 / 4
@test aic(repeat(e, 10), 3) ≈ log(sum(abs2, e) / 4) + 2 * 3 / 40

@test sse(y)[] ≈ sum(abs2, y)
@test mse(y)[] ≈ mean(abs2, y)

Expand Down
Loading