diff --git a/docs/src/examples/delayest.md b/docs/src/examples/delayest.md index a0ebf81f..26a3fecc 100644 --- a/docs/src/examples/delayest.md +++ b/docs/src/examples/delayest.md @@ -1,20 +1,24 @@ # Delay estimation -A frequent property of control systems is the presence of _delays_, either due to processing time, network latency, or other physical phenomena. Delays that occur internally in the system will in the discrete-time setting add a potentially large number of states to the system, ``\tau / T_s`` state variables are required to represent a delay of ``\tau`` seconds in a discrete-time system with sampling time ``T_s``. A common special case is that the delay occurs at either the input or the output of the system, e.g, due to communication delays. Estimating this delay ahead of the estimation of the model is often beneficial, since it reduces the number of parameters that need to be estimated. Below, we generate a dataset with a large input delay ``\tau`` and have a look at how we can estimate ``\tau``. +A frequent property of control systems is the presence of _delays_, either due to processing time, network latency, or other physical phenomena. Delays that occur internally in the system will in the discrete-time setting add a potentially large number of state variables to the system, ``\tau / T_s`` state variables are required to represent a delay of ``\tau`` seconds in a discrete-time system with sampling time ``T_s``. A common special case is that the delay occurs at either the input or the output of the system, e.g, due to communication delays. Estimating this delay ahead of the estimation of the model is often beneficial, since it reduces the number of parameters that need to be estimated. Below, we generate a dataset with a large input delay ``\tau`` and have a look at how we can estimate ``\tau``. ## Estimating the delay +The simulated experiments start at rest, and the data are noise-free unless stated otherwise. ```@example DELAY -using DelimitedFiles, Plots +using Plots, Random using ControlSystemIdentification, ControlSystemsBase gr(fmt=:png) # hide +Random.seed!(1) τ = 2.0 # Delay in seconds Ts = 0.1 # Sampling time +τ_samples = round(Int, τ / Ts) # Delay in samples P = c2d(tf(1, [1, 0.5, 1])*delay(τ), Ts) # Dynamics is given by a simple second-order system with input delay -u = sin.(0.1 .* (0:Ts:30).^2) # An interesting input signal -res = lsim(P, u', x0=[0.5; 0; zeros(20)]) +colored(N) = lsim(tf(1, [1, -0.9], Ts), randn(1, N))[1] # Random signal with most of its power at low frequencies +u = colored(600) +res = lsim(P, u) d = iddata(res) plot(d) ``` @@ -24,19 +28,34 @@ If we inspect the (discrete-time) system, we see that it indeed has a large-dime P.nx ``` +### The delay convention +A discrete-time system that is strictly proper has at least a one-sample delay between the input and the output, the output at time ``k`` cannot depend on the input at time ``k``. The `inputdelay` keyword of, e.g., [`arx`](@ref) counts this sample: the default `inputdelay = 1` is a system without any additional delay, `inputdelay = 0` is a system with a direct term, and a strictly proper system with a relative degree of one and a pure delay of ``n`` samples has `inputdelay = n + 1` (in general, `inputdelay = n + r` for a relative degree ``r``). The system `P` above has a pure delay of `τ_samples` samples, and thus corresponds to `inputdelay = τ_samples + 1`. We will use this convention throughout this page. + A simple, non-parametric way of figuring out whether or not there's a delay in the system is to look at the cross-correlation between the input and the output, we can do this using the [`crosscorplot`](@ref) function: ```@example DELAY crosscorplot(d) ``` -The plot indicates that there is insignificant (below the dashed lines) correlation between the input and the output for lags smaller than 2 seconds, corresponding exactly to our delay ``\tau``. +The dashed lines indicate the confidence interval within which the correlation is considered insignificant, but they are only valid if the input is white. The cross-correlation between the input and the output is the impulse response of the system convolved with the autocorrelation of the input. If the input is not white, as in this case, the autocorrelation of the input causes a correlation to appear also at lags that are _shorter_ than the delay, and the plot above indicates a significant correlation at lags well below the true delay of two seconds. + +To remedy this, we _prewhiten_ the input: we estimate an autoregressive model [`ar`](@ref) of the input, and filter both the input and the output through the inverse of this model. Since the same linear filter is applied to both signals, the delay is unaffected, but the input is now approximately white and the confidence bounds are valid: + +```@example DELAY +function prewhiten(d, na = 5) + Gar = ar(iddata(d.u, d.Ts), na) # Model of the input signal, Gar = 1/A + W = 1/Gar # Whitening filter A + iddata(lsim(W, d.y)[1], lsim(W, d.u)[1], d.Ts) +end +crosscorplot(prewhiten(d)) +``` +The prewhitened cross-correlation is insignificant for lags shorter than the delay, and starts to rise at a lag of two seconds plus one sample, in agreement with the convention above. The estimate obtained in this way is an approximation: the correlation exceeds the confidence interval some samples after the true delay since the impulse response of the system without delay starts at zero, and the dashed lines are valid for each lag individually, meaning that a few lags are expected to exceed them by chance in a long plot. Another method to identify the delay would be to estimate the impulse response of the system: ```@example DELAY impulseestplot(d, 60; λ=0.5, lab="Estimated", title="Impulse response of delay system") plot!(impulse(P, 6), lab="True", framestyle=:zerolines) ``` -Estimation of impulse responses in the presence of such large delays is numerically challenging, and a regularization of ``λ=0.5`` was required to achieve a reasonable result. If the delay is expected to be large and the dataset is small, it is thus recommended to use the cross-correlation method instead, since we cannot tune the regularization parameter ``λ`` in a practical setting when we don't know what impulse response to expect. However, for short delays and large datasets, the impulse-response method works rather well. Below, we show the estimated impulse response for a much larger dataset just to demonstrate: +Estimation of impulse responses in the presence of such large delays is numerically challenging, and a regularization of ``λ=0.5`` was required to achieve a reasonable result. If the delay is expected to be large and the dataset is small, the cross-correlation method may be preferable, since the regularization parameter ``λ`` must be tuned, e.g., by evaluating the simulation fit of the estimated impulse response on a separate validation dataset, and the result depends on the excitation and the noise level. However, for short delays and large datasets, the impulse-response method works rather well. Below, we show the estimated impulse response for a much larger dataset just to demonstrate: ```@example DELAY u2 = sin.(0.01 .* (0:Ts:300).^2) .+ randn.() # An interesting and long input signal with some noise as well res2 = lsim(P, u2') @@ -46,28 +65,67 @@ impulseestplot(d2, 200; λ=0.0, lab="Estimated", title="Impulse response with la plot!(impulse(P, 20), lab="True", framestyle=:zerolines) ``` -A third method, arguably less elegant, is to use a model-selection method to figure out the delay. Presumably, models estiamted with an order smaller than the delay will be rather poor, something that should be visible if we try models of many orders. Below, we use the function [`find_nanb`](@ref) that tries to identify the appropriate model order for an [`arx`](@ref) model. +The impulse response is estimated by fitting a long FIR model, which has many parameters and is sensitive to noise. This can be mitigated by regularization with a parameter ``λ``, which introduces a bias towards small impulse-response coefficients in exchange for a lower variance. The regularization parameter is not known beforehand, but it _can_ be tuned using data: we estimate the impulse response for a number of values of ``λ`` using one dataset, and evaluate the simulation fit of the corresponding FIR models on a second dataset obtained from a separate experiment. We add measurement noise to both datasets to make this realistic: + +```@example DELAY +σ = 0.1 # Standard deviation of the measurement noise +noisy(N) = (u = colored(N); iddata(lsim(P, u)[1] .+ σ*randn(1, N), u, Ts)) +dn, dval = noisy(200), noisy(200) # Estimation and validation data + +n = 100 # Number of FIR coefficients +λs = exp10.(-4:0.5:3) +fits = map(λs) do λ + ir, _ = impulseest(dn, n; λ) + Gfir = tf(Ts .* ir, [1; zeros(n - 1)], Ts) # impulseest returns the impulse response divided by Ts + modelfit(dval.y, lsim(Gfir, dval.u)[1])[] +end +λbest = λs[argmax(fits)] +plot( + plot(λs, fits, xscale=:log10, xlabel="λ", ylabel="Validation fit [%]", m=:o, legend=false), + impulseestplot(dn, n; λ=λbest, lab="Estimated", title="Impulse response, λ = $(round(λbest, sigdigits=2))"), + size=(900, 300), +) +plot!(impulse(P, 10), lab="True", framestyle=:zerolines, sp=2) +``` +The dashed lines in the right plot indicate an approximate interval of two standard deviations of the estimate, which does not account for the bias introduced by the regularization. The validation curve shows how the choice of ``λ`` is a trade-off between bias and variance: for small values the FIR model, which has about as many parameters as there are samples, adapts to the noise, and for large values the impulse response is suppressed. The best validation fit is obtained for an intermediate value. The number of coefficients `n` must be large enough to cover both the delay and the response of the system, and the result depends on the excitation, the number of samples and the noise level, and not only on the delay. If the dataset is small, the cross-correlation and the delay sweep below are less demanding alternatives. + +A third method, arguably less elegant, is to use a model-selection method to figure out the delay. Presumably, models estimated with an order smaller than the delay will be rather poor, something that should be visible if we try models of many orders. Below, we use the function [`find_nanb`](@ref) that tries to identify the appropriate model order for an [`arx`](@ref) model. Information criteria such as AIC are not informative for noise-free data, since the prediction error vanishes for all models of sufficient order, we thus use the noisy dataset. ```@example DELAY -find_nanb(d, 2:8, 10:30, xrotation=90, size=(800, 300), margin=5Plots.mm, xtickfont=6) +find_nanb(dn, 2:8, 10:30, xrotation=90, size=(800, 300), margin=5Plots.mm, xtickfont=6) ``` -The plot indicates that the Akaike information criterion (AIC) is minimized when `nb` reaches 22, which happens to be the number of delay samples ``\tau / T_s`` + the number of numerator parameters for the system without delay: +The prediction error tends to decrease once `nb` is large enough to cover the delay, which happens to be the number of delay samples ``\tau / T_s`` + the number of numerator parameters for the system without delay: ```@example DELAY c2d(tf(1, [1, 0.5, 1]), Ts) ``` +The criterion does not have a sharp minimum in this case, and models with a smaller `nb` and a dedicated `inputdelay` are more parsimonious, which is the approach of [`find_delay`](@ref). + + +A fourth method is to estimate a low-order model for each of a number of candidate delays, and compare how well the models explain the validation data. The function [`find_delay`](@ref) fits an [`arx`](@ref) model with `inputdelay = k` for each candidate `k` and returns the one with the smallest simulation error on the validation data. The orders `na` and `nb` should be chosen to represent the system _without_ delay, and `nb` should not be much larger than the number of numerator coefficients of that system, since a long B polynomial can compensate a too short delay on its own. The delay-free system above has two numerator coefficients, and two poles. Since [`arx`](@ref) is biased by output noise, we choose a slightly larger `na` for the noisy data: + +```@example DELAY +sweep = find_delay(dn, 6, 4, 0:40; dval) +``` +```@example DELAY +plot(sweep) +``` +The simulation error has a distinct minimum, which is located at or near the true delay of `τ_samples + 1` samples. Values of the loss larger than a fixed bound are clipped in the plot, e.g., those of unstable candidate models. The accuracy of the estimate decreases with the noise level, in particular if `na` is chosen too small, in which case the estimate is biased. The sweep is nevertheless a useful first step, since it reduces the problem to estimating the dynamics without a delay. For noise-free data, the true delay is recovered exactly: + +```@example DELAY +sweep_noisefree = find_delay(d, 2, 2, 0:40; dval = iddata(lsim(P, colored(600)))) +``` ## Handling the delay when estimating a model Once we know that there is a delay present, we need to somehow handle it while estimating a model. The naive way is to simply select a model with high-enough order and call it a day. However, this is prone to numerical problems and generally not recommended. Some methods have a dedicated `inputdelay` keyword that allows you to specify known input delays, after which the method handles it internally. For methods that do not have this option, one can always preprocess the data to remove the delay, we show how to do this next: ```@example DELAY -τ_samples = 20 # Number of samples delay -d2 = iddata(d.y[:, τ_samples+1:end], d.u[:, 1:end-τ_samples], d.Ts) -crosscorplot(d2) +d_shifted = iddata(d.y[:, τ_samples+1:end], d.u[:, 1:end-τ_samples], d.Ts) +crosscorplot(prewhiten(d_shifted)) ``` -The cross-correlation plot now indicates that the delay is gone. Please note, one sample delay is most of the time expected, indeed, it's unrealistic for the output of a physical system to respond at the same time as something happens at the input. Once we have estimated a model with the dataset with the delay removed, we must add the delay back into the estimated model, e.g., +The (prewhitened) cross-correlation plot now indicates that the delay is gone. Please note, one sample delay is most of the time expected, indeed, it's unrealistic for the output of a physical system to respond at the same time as something happens at the input. Once we have estimated a model with the dataset with the delay removed, we must add the delay back into the estimated model, e.g., ```@example DELAY -P̂ = subspaceid(d2, focus=:simulation) # Estimate a model without delay +P̂ = subspaceid(d_shifted, focus=:simulation) # Estimate a model without delay tf(d2c(P̂)) # Does it match the original continuous-time system without delay? ``` The estimated model above should be very close to the system `tf(1, [1, 0.5, 1])` (some small higher-order terms in the numerator are expected). To add the delay to this model, we do @@ -77,6 +135,9 @@ bodeplot([P, P̂τ], lab=["True system" "" "Estimated system" ""]) ``` The estimated model should now match the true system very well, including the large drop in phase for higher frequencies due to the delay. +!!! note "Input delay or output delay" + For a single-input single-output transfer function, `P̂*delay(τ, Ts)` and `delay(τ, Ts)*P̂` are the same transfer function. They are, however, different state-space realizations with different state variables: the delay state variables are located before or after the dynamics, so the initial state of the model has a different interpretation, and the estimated state of a state estimator built on the model is different. For multiple-input systems, an input delay and an output delay are different systems. + !!! warning "Internal delays" If the system contains internal delays, it might appear in a cross-correlation plot as if the system has an input-output delay, but in this case shifting the data like we did above may be ill-advised. With internal delays, use the number of estimated delay samples as a lower bound on the model order instead. An example of an internal delay is when a control loop is closed around a delayed channel, illustrated below. @@ -94,10 +155,10 @@ plot(nyquistplot(L), plot(step(G, 50))) ``` ```@example DELAY -ref = sign.(sin.(0.02 .* (0:Ts:50).^2)) # An interesting reference signal -res = lsim(G, ref') +ref = colored(500) # Reference signal +res = lsim(G, ref) dG = iddata(res) -plot(plot(dG), crosscorplot(dG)) +plot(plot(dG), crosscorplot(prewhiten(dG))) ``` We see that the cross-correlation plot still indicates that it takes over 2 seconds for the output to be affected by the input, but if we look at the model-selection plot, we must include orders up to above 23 to get a good fit: @@ -134,9 +195,15 @@ simplot(model, dG, zeros(model.nx)) In a practical scenario, estimating a model of such high order may be difficult. It might then be worthwhile trying to estimate the lower-order open-loop system ``P`` directly, taking care to properly handle the delay, which then appears on the input rather than internally. -If we use one of the methods that support the `inputdelay` keyword, we can see whether or not we can approximate the closed-loop system with a model that has an input delay only: +If we use one of the methods that support the `inputdelay` keyword, we can see whether or not we can approximate the closed-loop system with a model that has an input delay only. We let the delay sweep select the delay, and compare the validation error to the error of the candidate models: +```@example DELAY +dGval = iddata(lsim(G, colored(500))) # Validation data from a separate experiment +sweepG = find_delay(dG, 4, 4, 0:40; dval = dGval) +plot(sweepG) +``` +The simulation error on the validation data has a distinct minimum, and is small in absolute terms (the normalized RMS error is displayed in the figure), which indicates that the closed-loop system is well approximated by a model of low order with an input delay. Note that the selected delay does not have to equal the delay of the open-loop system exactly: the delayed channel is inside of the loop, and the estimated model is an approximation of the closed-loop system. We estimate a model with the selected delay: ```@example DELAY -model2 = arx(dG, 4, 4, inputdelay=τ_samples) +model2 = arx(dG, 4, 4, inputdelay=sweepG.delay) plot( simplot(model2, dG), pzmap( @@ -148,7 +215,7 @@ plot( ) ) ``` -We see that with a model of order 3 (4 free parameters in the denominator) together with a specified input delay of 20 samples, we indeed get a good approximation of the closed-loop system. +We see that with a model of order 4 (4 free parameters in the denominator) together with a specified input delay of `sweepG.delay` samples, we indeed get a good approximation of the closed-loop system. If we compare the Bode plots of the true closed-loop system with the two identified models, they match very well. ```@example DELAY @@ -158,10 +225,10 @@ bodeplot([G, model, model2]) It may thus be possible to approximate a system with internal delays using a model that has an input delay only. -For completeness, we construct an example where this is not quite possible. The system in the example below can be thought of as an echo chamber, where the input passes through a resonant channel before it reaches the output. 60% of the output energy is fed back at the input through the same channel (the echo), causing an interesting impulse response: +For completeness, we construct an example where this is not quite possible. The system in the example below can be thought of as an echo chamber, where the input passes through a resonant channel before it reaches the output. A fraction of the output, with a gain of 0.6 at low frequencies, is fed back at the input through the same channel (the echo), causing an interesting impulse response: ```@example DELAY ref = sign.(sin.(0.02 .* (0:Ts:100).^2)) # An interesting reference signal -Pc = feedback(tf(100, [1, 10, 100]), -tf(60, [1, 10, 100])*delay(τ)) # Feed 60% of the output back at the input with a delay of 2 seconds (like an echo) +Pc = feedback(tf(100, [1, 10, 100]), -tf(60, [1, 10, 100])*delay(τ)) # Feed the output back at the input with a low-frequency gain of 0.6 and a delay of 2 seconds (like an echo) Pd = c2d(Pc, Ts) res = lsim(Pd, ref') decho = iddata(res) @@ -173,9 +240,15 @@ The model-selection plot below indicates that we need to reach model orders of 2 find_nanb(decho, 3:30, 5:30, xrotation=90, size=(800, 300), margin=5Plots.mm, xtickfont=6) ``` -trying to estimate a 4:th order model with input delay of 20 samples does not work at all this time, but fitting a 24:th order model does, and fitting a 4:th order model using subspace identification with a long internal prediction horizon works reasonably well +This time, the delay sweep does not find any delay for which a low-order model with an input delay fits the data well, in contrast to the previous example. Note that the candidate delays include zero: the forward path of this system does not contain any transport delay, the output starts to respond to the input after the minimum delay of the delay-free dynamics, and a model with a long input delay is thus not a suitable structure: +```@example DELAY +sweepE = find_delay(decho, 4, 4, 0:40) +plot(sweepE) +``` + +trying to estimate a 4:th order model with input delay of 21 samples does not work at all this time, but fitting a 24:th order model does, and fitting a 4:th order model using subspace identification with a long internal prediction horizon works reasonably well ```@example DELAY -model3 = arx(decho, 4, 4, inputdelay=τ_samples) +model3 = arx(decho, 4, 4, inputdelay=τ_samples+1) model4 = subspaceid(decho, 24) model5 = subspaceid(decho, 4, r=50) figsim = simplot(model3, decho, zeros(ss(model3).nx), sysname="ARX 4") @@ -238,7 +311,7 @@ bodeplot!(model_sim, lab="Simulation model") bodeplot!(model_pred, lab="Prediction model", legend=:bottomleft) ``` -We see that although the result is not perfect, we do have one state variable to little after all, the fit is much better. This also carries over to the time domain: +We see that although the result is not perfect, we do have one state variable too few after all, the fit is much better. This also carries over to the time domain: ```@example DELAY plot(res, lab="Data") simplot!(model_sim, d, ploty=false, sysname="Simulation model") diff --git a/src/ControlSystemIdentification.jl b/src/ControlSystemIdentification.jl index 12468dd6..2b38353c 100644 --- a/src/ControlSystemIdentification.jl +++ b/src/ControlSystemIdentification.jl @@ -76,6 +76,8 @@ 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") @@ -83,6 +85,7 @@ include("types.jl") include("frd.jl") include("pem.jl") include("arx.jl") +include("delay.jl") include("subspace.jl") include("subspace2.jl") include("spectrogram.jl") diff --git a/src/delay.jl b/src/delay.jl new file mode 100644 index 00000000..7176439d --- /dev/null +++ b/src/delay.jl @@ -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 diff --git a/src/utils.jl b/src/utils.jl index 0ba6cad7..400deaef 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -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 diff --git a/test/runtests.jl b/test/runtests.jl index 81d4bb0c..2d5be439 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -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") diff --git a/test/test_delay.jl b/test/test_delay.jl new file mode 100644 index 00000000..bc49b46e --- /dev/null +++ b/test/test_delay.jl @@ -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) diff --git a/test/test_utils.jl b/test/test_utils.jl index ec095197..f9eb503f 100644 --- a/test/test_utils.jl +++ b/test/test_utils.jl @@ -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) @@ -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)