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

Allow iterators of unknown size in macros #2550

Merged
merged 7 commits into from
Apr 7, 2021
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
11 changes: 10 additions & 1 deletion src/Containers/vectorized_product_iterator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,17 @@ For instance:
struct VectorizedProductIterator{T}
prod::Iterators.ProductIterator{T}
end

# Collect iterators with unknown size so they can be used as axes.
_collect(::Base.SizeUnknown, x) = collect(x)
_collect(::Any, x) = x
function _collect(::Base.IsInfinite, x)
return error("Unable to form a container. Axis $(x) has infinite size!")
end
_collect(x) = _collect(Base.IteratorSize(x), x)

function vectorized_product(iterators...)
return VectorizedProductIterator(Iterators.product(iterators...))
return VectorizedProductIterator(Iterators.product(_collect.(iterators)...))
end
function Base.IteratorSize(
::Type{<:VectorizedProductIterator{<:Tuple{Vararg{Any,N}}}},
Expand Down
11 changes: 11 additions & 0 deletions test/Containers/vectorized_product_iterator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,14 @@ using Test
@test collect(Containers.vectorized_product(2, I)) ==
[(2, 1) (2, 3) (2, 2) (2, 4)]
end

@testset "Unknown size" begin
f = Iterators.filter(k -> isodd(k), 1:10)
v = Containers.vectorized_product(f)
@test axes(v) == (Base.OneTo(5),)
end

@testset "Infinite size" begin
f = Iterators.repeated(1)
@test_throws ErrorException Containers.vectorized_product(f)
end
14 changes: 14 additions & 0 deletions test/variable.jl
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,20 @@ function test_Model_relax_integrality_error_cases(::Any, ::Any)
@test_throws err relax_integrality(model)
end

function test_unknown_size_dense(::Any, ::Any)
model = Model()
f = Iterators.filter(k -> isodd(k), 1:10)
@variable(model, x[f])
@test length(x) == 5
end

function test_unknown_size_sparse(::Any, ::Any)
model = Model()
f = Iterators.filter(k -> isodd(k), 1:10)
@variable(model, x[i = f; i < 5])
@test length(x) == 2
end

function test_start_value(::Any, ::Any)
model = Model()
@variable(model, x)
Expand Down