Piecewise-constant fitting

Is it possible to constrain it to have a minimum distance between breakpoints, to avoid very short steps?

Yes. Constrain z so that it can change value only once in a given window:

window = 10
@constraint(model, [i=window:N], sum(z[i-j+1] for j in 1:window) <= 1)

This guy needs special installation. Why do we need it? Are there any alternatives?

If you’re an academic you can get a free license. We need a mixed-integer quadratic solver. There aren’t many great free alternatives.

If you use the L1 norm for the loss function instead of the L2, then you can use HiGHS:

using JuMP, HiGHS, Plots
K = 21
δ = maximum(y) - minimum(y)
model = Model(HiGHS.Optimizer)
set_time_limit_sec(model, 30)
@variables(model, begin
    x[1:N]
    z[1:N], Bin
    t
end)
window = 10
@constraints(model, begin
    sum(z) <= K - 1
    [i=window:N], sum(z[i-j+1] for j in 1:window) <= 1
    [i=2:N], x[i] - x[i-1] <= z[i] * δ
    [i=2:N], x[i] - x[i-1] >= -z[i] * δ
    [t; y .- x] in MOI.NormOneCone(1 + N)
end)
@objective(model, Min, t);
optimize!(model)
plot(y)
plot!(value.(x))

6 Likes