Can you control how JuMP prints indexes in print(model)
beyond overriding Base.show
? If not, this would be a nice, but not super-important feature.
Take as an example, an excerpt from the JuMP knapsack example, but instead we use structs
:
struct Item
name::String
profit::Float64
weight::Float64
end
items = [
Item("TV", 5, 2),
Item("Fridge", 3, 8),...
]
@variable(model, x[items], Bin)
...
If I print the model, elements of x
will be printed as x[Item("TV", 5.0, 2,0)]
, which is ok.
I can do better by defining
function Base.show(io::IO, i::Item)
print(io, i.name)
end
and then x
s will be x[TV]
in the print out of the model. The problem here is that as far as I know, there’s only one Base.show
, and you can’t pass any formatting information to it, and in other situations I might wish to show
an Item
differently.
I work around this by doing things like putting the Item
s in a dictionary:
items = Dict(
"TV" = Item("TV", 5, 2),...
)
@variable(model, x[keys(items)], Bin)
@constraint(model, sum(i.weight * x[key] for (key, i) in items) <= capacity)
But that makes the model unnecessarily complicated.
It would be really nice if there was something like a:
show_as_index(io:IO, x) = Base.show(io, x)
In JuMP so you could override show_as_index
.
Are there any obvious solutions I am missing? This is a really minor gripe, but I’m working on some simple examples of using JuMP as tutorilals, and this would make the examples even simpler.
Thanks!