# Fitting gaussian to spectral data has unexpected results

**URL:** https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961
**Category:** General Usage
**Tags:** curve-fitting, lsqfit
**Created:** [September 2, 2024, 8:37pm UTC](https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961 "2024-09-02T20:37:55Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![Amnesian](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/amnesian/32/209210_2.png) [@Amnesian](https://discourse.julialang.org/u/Amnesian)
#### Post date: [September 2, 2024, 8:37pm UTC](https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961/1 "2024-09-02T20:37:55Z")

</div>

[My data](https://github.com/AmnesianBlizzard/temp-data/blob/main/Hg_lamp.csv)  
Trying to fit a gaussian (not `Normal`, because it has arbitrary amplitude) on a peak in my data produces very bad parameter values. Expected should be close to my initial guesses, but it outputs [14936.170188518823, 1.1517122795420878e6, 886780.0024262934].  
If I try to add upper or lower bounds, it just spits them back at me. If I make the bounds too close to each other, it spits my initial guess back at me.

I’m not really too sure how to fix this as my experience in “curve fitting theory” is practically zero.

Another issue that I came across is that if I give it integers as initial guesses, then the fitting breaks and gives me `Inexact Error: Int64(NaN)`, which doesn’t tell me anything useful.

Code example:

```julia
function import_data(pattern::String=".csv"; directory::String="./")
        filenames = filter(x -> occursin(pattern, x), readdir(directory))
        data = CSV.read.(filenames, DataFrame, header=["Index", "Pixel", "Amplitude"], drop=[:Index], skipto=2)
        return (filenames, data)
    end
    _, data = import_data()

    gauss(x, A, μ, σ) = A * exp(-0.5(x - μ)^2 / σ^2)
    log_gauss(x, A, μ, σ) = A - 0.5(x - μ)^2 / σ^2
    dat = data[1][1620:1640, :]
    @. model(x, p) = gauss(x, p[1], p[2], p[3])
    p0 = [1.0, 1650.0, 2.0]
    fit = curve_fit(model, dat.Pixel, dat.Amplitude, p0)
    coef(fit)

```

Error stack trace for the integer initial guessing problem:

> Stacktrace:  
> [1] Int64(x::Float64)  
> @ Base .\float.jl:912  
> [2] alloc\_DF(x::Vector{Int64}, F::Vector{Float64})  
> @ NLSolversBase C:\Users\Jacques.julia\packages\NLSolversBase\kavn7\src\objective\_types\abstract.jl:19  
> [3] lmfit(f::LsqFit.var"#18#20"{…}, p0::Vector{…}, wt::Vector{…}; autodiff::Symbol, kwargs::@Kwargs{})  
> @ LsqFit C:\Users\Jacques.julia\packages\LsqFit\OglWj\src\curve\_fit.jl:71  
> [4] lmfit(f::Function, p0::Vector{Int64}, wt::Vector{Int64})  
> @ LsqFit C:\Users\Jacques.julia\packages\LsqFit\OglWj\src\curve\_fit.jl:54  
> [5] curve\_fit(model::var"#model#278"{…}, xdata::Vector{…}, ydata::Vector{…}, p0::Vector{…}; inplace::Bool, kwargs::@Kwargs{})  
> @ LsqFit C:\Users\Jacques.julia\packages\LsqFit\OglWj\src\curve\_fit.jl:140  
> [6] curve\_fit(model::Function, xdata::Vector{Int64}, ydata::Vector{Int64}, p0::Vector{Int64})  
> @ LsqFit C:\Users\Jacques.julia\packages\LsqFit\OglWj\src\curve\_fit.jl:123

---

<div class="post-metadata">

### Author: ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)
#### Post date: [September 3, 2024, 10:25am UTC](https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961/2 "2024-09-03T10:25:24Z")

</div>

That’s not so surprising, its method is not numerically stable. Did you try NonlinearSolve.jl’s NonlinearLeastSquaresProblem? I don’t have your data to slap it in there and check.

---

<div class="post-metadata">

### Author: ![Amnesian](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/amnesian/32/209210_2.png) [@Amnesian](https://discourse.julialang.org/u/Amnesian)
#### Post date: [September 3, 2024, 11:27am UTC](https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961/3 "2024-09-03T11:27:53Z")

</div>

My data is in the link at the top of the OP.

I’m not quite sure how to include data (list/s of x , y) into this object. It seems to just take in a model, initial guess and parameters. And once I’ve done this, do I call solve() on it?

I currently have something that looks like this  
`NonlinearLeastSquaresProblem(gauss(x, A, μ, σ), [1, 1650, 2], [A, μ, σ])` I’m not sure if I’m interpreting their documentation correctly

---

<div class="post-metadata">

### Author: ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)
#### Post date: [September 4, 2024, 11:58am UTC](https://discourse.julialang.org/t/fitting-gaussian-to-spectral-data-has-unexpected-results/118961/4 "2024-09-04T11:58:54Z")

</div>

> [@Amnesian](#):
>
> I’m not quite sure how to include data (list/s of x , y) into this object. It seems to just take in a model, initial guess and parameters. And once I’ve done this, do I call solve() on it?

Yes. Data is Just a parameter so you add that and call solve.
