Skip to content

Commit fcb754c

Browse files
fix: handle broadcast allocation for range-backed QuantityArray (#218)
* fix: handle broadcast allocation for range-backed QuantityArray Co-authored-by: Miles Cranmer <miles.cranmer@gmail.com> * refactor: use @eval loop for quantity array similar Co-authored-by: Miles Cranmer <miles.cranmer@gmail.com> --------- Co-authored-by: Miles Cranmer <miles.cranmer@gmail.com>
1 parent 0341715 commit fcb754c

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

src/arrays.jl

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -315,8 +315,13 @@ function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{QA}}, ::Typ
315315
first_output::ElType = materialize_first(bc)
316316
return QuantityArray(output_array, dimension(first_output)::dim_type(ElType), ElType)
317317
end
318-
function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{QuantityArray{T,N,D,Q,V}}}, ::Type{ElType}) where {T,N,D,Q,V<:Array{T,N},ElType}
319-
return similar(Array{ElType}, axes(bc))
318+
for VSupertype in (:(Array{T,N}), :(AbstractRange{T}))
319+
@eval function Base.similar(
320+
bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{QuantityArray{T,N,D,Q,V}}},
321+
::Type{ElType},
322+
) where {T,N,D,Q,V<:$VSupertype,ElType}
323+
return similar(Array{ElType}, axes(bc))
324+
end
320325
end
321326
function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{QuantityArray{T,N,D,Q,V}}}, ::Type{ElType}) where {T,N,D,Q,V,ElType}
322327
# To deal with things like StaticArrays, we need to rely on

test/unittests.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,19 @@ end
482482
@test RealQuantity(us"inch") * (1.0:4.0) isa QuantityArray
483483
end
484484

485+
@testset "Broadcasting over QuantityArray with StepRangeLen backing" begin
486+
struct WrappedQuantity{T}
487+
value::T
488+
end
489+
490+
t = QuantityArray(range(1.0, step=0.1, length=10), u"s")
491+
wrapped = WrappedQuantity.(t)
492+
493+
@test wrapped isa Vector{WrappedQuantity{Quantity{Float64,typeof(dimension(u"s"))}}}
494+
@test first(wrapped).value == first(t)
495+
@test last(wrapped).value == last(t)
496+
end
497+
485498
@testset "Array of quantities multiplication behavior" begin
486499
# Test that array of quantities * quantity does NOT create nested QuantityArray
487500
# but instead broadcasts properly

0 commit comments

Comments
 (0)