Skip to content

Support for Unitful.jl's units?Β #250

@singularitti

Description

@singularitti

Would you consider supporting fitting x- and y-data which has units that are defined by Unitful.jl?
For example,

using LsqFit
@. model(x, p) = p[1]*exp(-x*p[2])
xdata = range(0, stop=10, length=20) .* u"m"
ydata = model(xdata, [1.0u"kg" 2.0u"m^-1"]) + 0.01u"g" * randn(length(xdata))
p0 = [0.5u"kg", 0.5u"m^-1"]
fit = curve_fit(model, xdata, ydata, p0)

I'm having the following stacktrace:

ERROR: MethodError: no method matching (Quantity{Float64})(::Float64)

Closest candidates are:
  (::Type{T})(::T) where T<:Number
   @ Core boot.jl:790
  (::Type{<:Unitful.AbstractQuantity})(::Union{Dates.Day, Dates.Hour, Dates.Microsecond, Dates.Millisecond, Dates.Minute, Dates.Nanosecond, Dates.Second, Dates.Week})
   @ Unitful ~/.julia/packages/Unitful/J4AJj/src/dates.jl:60
  (::Type{<:Unitful.AbstractQuantity})(::Dates.CompoundPeriod)
   @ Unitful ~/.julia/packages/Unitful/J4AJj/src/dates.jl:135
  ...

Stacktrace:
 [1] alloc_DF(x::Vector{Quantity{Float64}}, F::Vector{Quantity{Float64, 𝐌, Unitful.FreeUnits{(kg,), 𝐌, nothing}}})
   @ NLSolversBase ~/.julia/packages/NLSolversBase/kavn7/src/objective_types/abstract.jl:19
 [2] lmfit(f::LsqFit.var"#18#20"{…}, p0::Vector{…}, wt::Vector{…}; autodiff::Symbol, kwargs::@Kwargs{})
   @ LsqFit ~/.julia/packages/LsqFit/OglWj/src/curve_fit.jl:71
 [3] lmfit(f::Function, p0::Vector{Quantity{Float64}}, wt::Vector{Quantity{Float64, 𝐌, Unitful.FreeUnits{(kg,), 𝐌, nothing}}})
   @ LsqFit ~/.julia/packages/LsqFit/OglWj/src/curve_fit.jl:54
 [4] curve_fit(model::typeof(model), xdata::StepRangeLen{…}, ydata::Vector{…}, p0::Vector{…}; inplace::Bool, kwargs::@Kwargs{})
   @ LsqFit ~/.julia/packages/LsqFit/OglWj/src/curve_fit.jl:140
 [5] curve_fit(model::Function, xdata::StepRangeLen{…}, ydata::Vector{…}, p0::Vector{…})
   @ LsqFit ~/.julia/packages/LsqFit/OglWj/src/curve_fit.jl:123

The problem seems to be in this line:

alloc_DF(x, F) = eltype(x)(NaN) .* vec(F) .* vec(x)'

Where x has eltype of Quantity{Float64}, which cannot apply onto NaN. I guess this can be changed since we are only allocating an array, where NaN does not really matter here.

Versions:

  • LsqFit v0.15.0
  • Julia: v1.10.0-rc1

Similar: #248 #143

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions