# Fitting gaussian to spectral data has unexpected results

My data
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:

``````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

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.

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

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