PainterQubits / Unitful.jl

Physical quantities with arbitrary units
Other
614 stars 112 forks source link

Dimensional correctness test with unknown constants (with unknown units) #653

Open MilesCranmer opened 1 year ago

MilesCranmer commented 1 year ago

I want to determine if an expression, with arbitrary constants, is dimensionally correct. The constants essentially have "wildcard" units which one would solve for to make an expression consistent. How can I do this with Unitful.jl?

For example,

I am wondering what the best way to approach this with Unitful.jl is?

MilesCranmer commented 1 year ago

Okay I think I got it working: https://github.com/MilesCranmer/SymbolicRegression.jl/pull/220. The trick is to define a wrapper type:

"""
    WildcardDimensionWrapper{T}

A wrapper for `Quantity{T}` that allows for a "wildcard" unit, indicating
there is a free constant whose dimensions are not yet determined.
Also stores a flag indicating whether an expression is dimensionally consistent.
"""
Base.@kwdef struct WildcardDimensionWrapper{T}
    val::Quantity{T} = one(Quantity{T})
    wildcard::Bool = false
    violates::Bool = false
end

and propagate wildcard through a depth-first tree traversal evaluation.

However, it is slow. I think this is due to the type instability in val, as the units are variable at each node in an expression. Is there any way I can get around this? Or maybe a type-stable version of Unitful.jl I could use?