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

[Useability] @constraint and @variable: cannot use an iterator #1915

Closed
dourouc05 opened this issue Mar 21, 2019 · 2 comments · Fixed by #2550
Closed

[Useability] @constraint and @variable: cannot use an iterator #1915

dourouc05 opened this issue Mar 21, 2019 · 2 comments · Fixed by #2550
Labels

Comments

@dourouc05
Copy link
Contributor

dourouc05 commented Mar 21, 2019

I am working with graphs, basically generating one variable per edge and then adding constraints. However, when I cannot use the usual syntax @variable(m, x[e in Iterators.filter(k -> true, edges(g))]), due to Iterators.filter(k -> true, edges(g)) returning an iterator whose size is unknown a priori:

ERROR: MethodError: no method matching length(::Base.Iterators.Filter{getfield(Main, Symbol("##1670#1674")),LightGraphs.SimpleGraphs.SimpleEdgeIter{SimpleDiGraph{Int64}}})
Closest candidates are:
  length(::Core.SimpleVector) at essentials.jl:582
  length(::Base.MethodList) at reflection.jl:732
  length(::Core.MethodTable) at reflection.jl:806
  ...

An minimum "working" example:

using JuMP, LightGraphs
g = PathGraph(3)
m = Model()
@variable(m, x[e in Iterators.filter(k -> true, edges(g))] = 0)

For anyone else facing this issue, the solution is simple: put a collect to transform the iterator into an array.

Shouldn't JuMP be doing it automatically? A test could be implemented on IteratorSize(IterType), to return more specific errors: if it is IsInfinite, it makes no sense; if it is SizeUnknown, JuMP should make an array out of the iterator first.

@mlubin
Copy link
Member

mlubin commented Mar 28, 2019

Sure, this would be nice to have. At the least, the error message is a bug because it violates the MethodError principle. That said, JuMP has a special syntax that coves the Iterators.filter case, e.g., @variable(m, x[e in edges(g); some_condition(e)]).

@blegat
Copy link
Member

blegat commented Mar 28, 2019

This might be resolve by #525 (comment) but in the short term, collecting it based in IteratorSize is a good idea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging a pull request may close this issue.

4 participants