Skip to content

Add uconvert method for QuantityArray #61

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

Merged
merged 2 commits into from
Oct 15, 2023
Merged
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: 10 additions & 0 deletions src/symbolic_dimensions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ function expand_units(q::Q) where {T,R,D<:SymbolicDimensions{R},Q<:AbstractQuant
return convert(constructor_of(Q){T,Dimensions{R}}, q)
end
expand_units(q::QuantityArray) = expand_units.(q)
# TODO: Make the array-based one more efficient

"""
uconvert(qout::AbstractQuantity{<:Any, <:SymbolicDimensions}, q::AbstractQuantity{<:Any, <:Dimensions})
Expand All @@ -121,6 +122,15 @@ function uconvert(qout::AbstractQuantity{<:Any, <:SymbolicDimensions}, q::Abstra
new_dim = dimension(qout)
return new_quantity(typeof(q), new_val, new_dim)
end
function uconvert(qout::AbstractQuantity{<:Any,<:SymbolicDimensions}, q::QuantityArray{<:Any,<:Any,<:Dimensions})
@assert isone(ustrip(qout)) "You passed a quantity with a non-unit value to uconvert."
qout_expanded = expand_units(qout)
dimension(q) == dimension(qout_expanded) || throw(DimensionError(q, qout_expanded))
new_array = ustrip(q) ./ ustrip(qout_expanded)
new_dim = dimension(qout)
return QuantityArray(new_array, new_dim, quantity_type(q))
end
# TODO: Method for converting SymbolicDimensions -> SymbolicDimensions

"""
uconvert(qout::AbstractQuantity{<:Any, <:SymbolicDimensions})
Expand Down
16 changes: 16 additions & 0 deletions test/unittests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,22 @@ end
qs = uconvert(convert(Quantity{Float16}, us"g"), 5 * q)
@test typeof(qs) <: Quantity{Float16,<:SymbolicDimensions{<:Any}}
@test qs ≈ 7.5us"g"

# Arrays
x = [1.0, 2.0, 3.0] .* u"kg"
xs = x .|> uconvert(us"g")
@test typeof(xs) <: Vector{<:Quantity{Float64,<:SymbolicDimensions{<:Any}}}
@test xs[2] ≈ 2000us"g"

x_qa = QuantityArray(x)
xs_qa = x_qa .|> uconvert(us"g")
@test typeof(xs_qa) <: QuantityArray{Float64,1,<:SymbolicDimensions{<:Any}}
@test xs_qa[2] ≈ 2000us"g"

# Without vectorized call:
xs_qa2 = x_qa |> uconvert(us"g")
@test typeof(xs_qa2) <: QuantityArray{Float64,1,<:SymbolicDimensions{<:Any}}
@test xs_qa2[2] ≈ 2000us"g"
end

@testset "Test ambiguities" begin
Expand Down