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

WIP: Experimental support for Unitful-like statically-typed units #136

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

MilesCranmer
Copy link
Member

@MilesCranmer MilesCranmer commented May 11, 2024

I understand this goes against the main point of this package, but it turned out to be extremely easy to stick in a StaticDimensions interface.

The trick is to store a regular dynamic Dimensions object (immutable struct) as one of the type parameters:

struct StaticDimensions{R,D<:AbstractDimensions{R},dim} <: AbstractStaticDimensions{R,D,dim}
    # (No fields)

    StaticDimensions(d::AbstractDimensions) = new{eltype(d),typeof(d),d}()
end

Promotion rules work as you'd expect with Unitful:

julia> using DynamicQuantities; using DynamicQuantities: StaticDimensions

julia> x = Quantity{Float64,StaticDimensions}.([1.0u"m", 1.0u"km", 10us"Constants.Mpc"])
3-element Vector{Quantity{Float64, StaticDimensions(m::Dimensions{FixedRational{Int32, 25200}})}}:
                  1.0 m
               1000.0 m
 3.085677581491367e23 m

Where you can see it correctly promotes the dimensions (even symbolic dimensions).

We can see that units can be inferred:

julia> x = Quantity{Float64,StaticDimensions}(10u"km")
10000.0 m

julia> y = Quantity{Float64,StaticDimensions}(1u"h")
3600.0 s

julia> @inferred x / y
2.7777777777777777 m s⁻¹

julia> typeof(x / y)
Quantity{Float64, StaticDimensions(m s⁻¹::Dimensions{FixedRational{Int32, 25200}})}

If anyone is interested, would love help in making this infer as well as Unitful. It then would make it really easy to switch between static and dynamic quantities – Dimensions for initial work, and then StaticDimensions whenever you are faced with optimizing a fast SIMD loop.

Any of @YingboMa @ChrisRackauckas @devmotion @aplavin, would you be up to help with improving this? I think the basics are ready, we would just need to ensure that inference is as good as Unitful.

This comment was marked as resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant