Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Measurements package extension #248

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,24 @@ NLSolversBase = "d41bc354-129a-5804-8e4c-c37616107c6c"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
StatsAPI = "82ae8749-77ed-4fe6-ae5f-f523153014b0"

[weakdeps]
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"

[extensions]
MeasurementsExt = "Measurements"

[compat]
Distributions = "0.18, 0.19, 0.20, 0.21, 0.22, 0.23, 0.24, 0.25"
ForwardDiff = "0.10"
Measurements = "2.10"
NLSolversBase = "7.5"
StatsAPI = "1"
julia = "1.6"

[extras]
Measurements = "eff96d63-e80a-5855-80a2-b1b0885c5ab7"
StableRNGs = "860ef19b-820b-49d6-a774-d7a799459cd3"
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"

[targets]
test = ["Test", "StableRNGs"]
test = ["Test", "StableRNGs", "Measurements"]
35 changes: 35 additions & 0 deletions ext/MeasurementsExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module MeasurementsExt

using LsqFit
isdefined(Base, :get_extension) ? (using Measurements) : (using ..Measurements)

function LsqFit.curve_fit(
model,
xdata::AbstractArray,
ydata::AbstractArray{Measurement{T}} where T,
p0::AbstractArray;
inplace=false,
kwargs...,
)
y = Measurements.value.(ydata)
ye = Measurements.uncertainty.(ydata)
Copy link

@aplavin aplavin Jan 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR's implementation seems to ignore correlation between measurements.
The point of Measurements.jl, the only reason they use a very involved implementation (compared to a much simpler one as in Uncertain.jl), is tracking correlation between variables. Ignoring them for fitting can easily be surprising for the user if they even catch it – otherwise it directly leads to incorrect results.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think maybe the covariance matrix might have to be used here instead, but I dont know if how the weights would need to be adjusted for that.

Copy link

@TheFibonacciEffect TheFibonacciEffect Jan 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a monte carlo simulation of a fit could be used as a test case? That way, we know that the uncertainties are taken into account correctly.
Possibly something like this:

using LsqFit
using LinearAlgebra
using Distributions
# create datapoints with noise and correalation
N = 10
x = range(0, stop=10, length=N)
corr = 0.5^2 * diagm(0 => 2*ones(N), 1 => ones(N-1), -1 => ones(N-1))

# define model function
@. model(x, p) = p[1] * sin(p[2] * x)

p0 = [1.0, 1.0]
p = []
for i in 1:10
    y = model(x, p0) + rand(MvNormal(corr))
    fit = curve_fit(model, x, y, p0)
    push!(p, fit.param)
end
p_mean = mean(p, dims=1)
p_cov = cov(p)

which samples from a distribution according to a given correalation matrix and makes a fit. The same result should then be reproduced by this code with Measurements.jl with a given covariance matrix, at least approximately.

wt = ye .^ -2
curve_fit(model, xdata, y, wt, p0; inplace=inplace, kwargs...)
end

function LsqFit.curve_fit(
model,
jacobian,
xdata::AbstractArray,
ydata::AbstractArray{Measurement{T}} where T,
p0::AbstractArray;
inplace=false,
kwargs...,
)
y = Measurements.value.(ydata)
ye = Measurements.uncertainty.(ydata)
wt = ye .^ -2
curve_fit(model, jacobian, xdata, y, wt, p0; inplace=inplace, kwargs...)
end

end # module
10 changes: 10 additions & 0 deletions src/LsqFit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ using StatsAPI: coef, confint, dof, nobs, rss, stderror, weights, residuals, vco

import Base.summary

#
function __init__()
@static if !isdefined(Base, :get_extension)
@require Measurements="eff96d63-e80a-5855-80a2-b1b0885c5ab7" begin
include("../ext/MeasurementsExt.jl")
end
end
end


include("geodesic.jl")
include("levenberg_marquardt.jl")
include("curve_fit.jl")
Expand Down
52 changes: 52 additions & 0 deletions test/measurements.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using LsqFit
using Measurements
using StableRNGs

@testset "MeasurementsExt" begin
model(x, p) = p[1] .* exp.(-x .* p[2])
ptrue = [10, 0.3]
x = LinRange(0, 2, 50)
y0 = model(x, ptrue)
σ = rand(1:5, 50)
y = y0 .± σ
wt = σ .^ -2
fit0 = curve_fit(model, x, y0, wt, ptrue) # fit to data using weights
fit1 = curve_fit(model, x, y, ptrue) # fit to data using Measurements
@test coef(fit0) ≈ coef(fit1)

# some example data
rng = StableRNG(125)
x = range(0, stop = 10, length = 20)
y0 = model(x, [1.0, 2.0]) + 0.01 * randn(rng, length(x))
σ = 0.01
y = y0 .± σ
wt = ones(length(x)) * σ .^ -2
p0 = [0.5, 0.5]

for ad in (:finite, :forward, :forwarddiff)
fit0 = curve_fit(model, x, y0, wt, p0; autodiff = ad)
fit1 = curve_fit(model, x, y, p0; autodiff = ad)
for fit in (fit0, fit1)
@test norm(fit.param - [1.0, 2.0]) < 0.05
@test fit.converged

# can also get error estimates on the fit parameters
errors = margin_error(fit, 0.05)
@test norm(errors - [0.021, 0.093]) < 0.01
end
end
# if your model is differentiable, it can be faster and/or more accurate
# to supply your own jacobian instead of using the finite difference
function jacobian_model(x, p)
J = Array{Float64}(undef, length(x), length(p))
J[:, 1] = exp.(-x .* p[2]) #dmodel/dp[1]
J[:, 2] = -x .* p[1] .* J[:, 1] #dmodel/dp[2]
J
end
jacobian_fit0 = curve_fit(model, jacobian_model, x, y0, wt, p0;show_trace=true)
jacobian_fit1 = curve_fit(model, jacobian_model, x, y, p0;show_trace=true)
for jacobian_fit in (jacobian_fit0, jacobian_fit1)
@test norm(jacobian_fit.param - [1.0, 2.0]) < 0.05
@test jacobian_fit.converged
end
end
2 changes: 1 addition & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using LsqFit, Test, LinearAlgebra
using NLSolversBase

my_tests = ["curve_fit.jl", "levenberg_marquardt.jl", "curve_fit_inplace.jl", "geodesic.jl"]
my_tests = ["curve_fit.jl", "levenberg_marquardt.jl", "curve_fit_inplace.jl", "geodesic.jl", "measurements.jl"]

println("Running tests:")

Expand Down
Loading