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
Support zero
for array with heterogeneous units
#472
Conversation
I think it would be better to add this to Julia itself (for all heterogeneous |
Makes sense. Lemme see if I can get a PR for Base, then. |
I don't think there's a reason to wait 2 years for a fix though. Might as well put a comment/issue to delete this after Base is fixed. |
This PR changes the behavior for arrays with heterogeneous units but fixed dimension: Before: julia> zero(Quantity{Int,Unitful.𝐋}[1u"m", 1u"mm"])
2-element Vector{Quantity{Int64, 𝐋}}:
0 m
0 m After: julia> zero(Quantity{Int,Unitful.𝐋}[1u"m", 1u"mm"])
2-element Vector{Quantity{Int64, 𝐋}}:
0 m
0 mm But I don’t think that’s too bad. Even the old behavior returned a vector with non-concrete eltype, (even though all elements are the same), so it will not worsen performance in this case. |
@@ -376,6 +376,7 @@ zero(x::Type{<:AbstractQuantity{T}}) where {T} = throw(ArgumentError("zero($x) n | |||
zero(x::Type{<:AbstractQuantity{T,D}}) where {T,D} = zero(T) * upreferred(D) | |||
zero(x::Type{<:AbstractQuantity{T,D,U}}) where {T,D,U<:ScalarUnits} = zero(T)*U() | |||
zero(x::Type{<:AbstractQuantity{T,D,U}}) where {T,D,U<:AffineUnits} = zero(T)*absoluteunit(U()) | |||
zero(x::AbstractArray{<:AbstractQuantity}) = map(zero,x) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
zero(x::AbstractArray{<:AbstractQuantity}) = map(zero,x) | |
zero(x::AbstractArray{T}) where {T<:Unitful.AbstractQuantity} = isconcretetype(T) ? fill!(similar(x), zero(T)) : map(zero, x) |
This way the old method is used if the array is homogeneous, which is faster according to my benchmarks.
This is replaced by #516, which supports arrays with unassigned elements as well. |
When working with ModelingToolkit, we often would like to have heterogeneous units within an vector of variables. Presently there's no method to create a
zero
array for such a case, which is often needed when doing solves or automatic differentiation.This construction only works if an appropriate template array already exists (ie, cannot be done abstractly). So there's no ambiguity about what the unit type is for each index.