# Piecewise-constant fitting

**URL:** <https://discourse.julialang.org/t/piecewise-constant-fitting/94091>\
**Category:** Optimization (Mathematical)\
**Tags:** jump, curve-fitting, convex-optimization, piecewise\
**Created:** [February 5, 2023, 1:45pm UTC](https://discourse.julialang.org/t/piecewise-constant-fitting/94091 "2023-02-05T13:45:53Z")\
**Posts on this page:** 2\
**Page:** 2

<div class="post-metadata">

**Author:** ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)\
**Post date:** [February 8, 2023, 11:29pm UTC](https://discourse.julialang.org/t/piecewise-constant-fitting/94091/21 "2023-02-08T23:29:22Z")

</div>

@stephenll, thanks for this very good advice.

There is the Julia [Changepoints.jl](https://github.com/JuliaPackageMirrors/Changepoints.jl) package that implements the PELT technique. The results below are really good, but I was only able to get K=21 breakpoints after trial and error, with no constraints available on minimum segment size. JuMP’s heavy weapons seem to be more versatile.

 ![Plots_Changepoints_PELT](https://global.discourse-cdn.com/julialang/original/3X/3/6/3601f24d12599a13f2cfd9bda9fa1ad240b5381b.png)

> **Changepoints.jl code**
>
> ```julia
> using Changepoints, Plots
> 
> pelt_cps, cost = @PELT vec(y_data) Normal(:?, 0.02)
> plot(y_data, c=:blues)
> vline!(pelt_cps, c=:red, lw=0.4, ls=:dash, title="PELT Changepoints.jl, σ=0.025 (➡ K=21)", titlefontsize=9)
> 
> ```

---

<div class="post-metadata">

**Author:** ![jd-foster](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jd-foster/32/35824_2.png) [@jd-foster](https://discourse.julialang.org/u/jd-foster)\
**Post date:** [February 9, 2023, 12:40am UTC](https://discourse.julialang.org/t/piecewise-constant-fitting/94091/22 "2023-02-09T00:40:42Z")

</div>

> [@rafael.guerra](#):
>
> `plot_pwc_data()` could be conveniently replaced by:  
> `plot!(t, f, lt=:step, c=:red, lw=2)`

Thanks, I wasn’t aware of this.

[Previous page](https://discourse.julialang.org/t/piecewise-constant-fitting/94091.md?page=1)
