Skip to content
Open
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
16 changes: 15 additions & 1 deletion src/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,21 @@ Get the dimensions of a quantity, returning an `AbstractDimensions` object.
"""
dimension(q::UnionAbstractQuantity) = q.dimensions
dimension(d::AbstractDimensions) = d
dimension(aq::AbstractArray{<:UnionAbstractQuantity}) = allequal(dimension.(aq)) ? dimension(first(aq)) : throw(DimensionError(aq[begin], aq[begin+1:end]))
function _parent_dimension(aq::AbstractArray{<:UnionAbstractQuantity})
p = parent(aq)
if p === aq || !(p isa AbstractArray{<:UnionAbstractQuantity})
return nothing
Comment thread
MilesCranmerBot marked this conversation as resolved.
end

return dimension(p)
end
function dimension(aq::AbstractArray{<:UnionAbstractQuantity})
if isempty(aq)
d = _parent_dimension(aq)
d === nothing || return d
end
return allequal(dimension.(aq)) ? dimension(first(aq)) : throw(DimensionError(aq[begin], aq[begin+1:end]))
end
dimension(_) = DEFAULT_DIMENSIONLESS_TYPE()

"""
Expand Down
11 changes: 10 additions & 1 deletion test/unittests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ function unsafe_isapprox(x, y; kwargs...)
return isapprox(ustrip(x), ustrip(y); kwargs...) && dimension(x) == dimension(y)
end

struct ParentWrappedArray{T,N,A<:AbstractArray{T,N}} <: AbstractArray{T,N}
parent::A
end
Base.parent(A::ParentWrappedArray) = A.parent
Base.size(A::ParentWrappedArray) = size(parent(A))
Base.getindex(A::ParentWrappedArray, I...) = parent(A)[I...]

# TODO: This is a bit hacky but is required to avoid ambiguities
Base.round(::Type{T}, x::SimpleRatio) where {T} = round(T, x.num // x.den)

Expand Down Expand Up @@ -1294,6 +1301,9 @@ end
# Test default constructors:
@test QuantityArray(ones(3), u"m/s") == QuantityArray(ones(3), length=1, time=-1)
@test typeof(QuantityArray(ones(3), u"m/s")) <: QuantityArray{Float64,1,<:Dimensions,<:constructorof(DEFAULT_QUANTITY_TYPE),<:Array}
@test dimension(QuantityArray(Matrix{Float64}(undef, 0, 6), Q(u"s"))) == dimension(Q(u"s"))
@test dimension(ParentWrappedArray(QuantityArray(Matrix{Float64}(undef, 0, 6), Q(u"s")))) == dimension(Q(u"s"))
@test DynamicQuantities._parent_dimension(Quantity[]) === nothing

# We can create quantity arrays with generic quantity
@test typeof(QuantityArray([[1.0], [2.0, 3.0]], dimension(u"m/s"))) <: QuantityArray{<:Any,1,<:Dimensions,<:GenericQuantity,<:Array}
Expand Down Expand Up @@ -2362,4 +2372,3 @@ using ExternalUnitRegistration: MyWb
end

pop!(LOAD_PATH)

Loading