I want to write a function
Hey there! I think you need to actually run the optimization with optimize!(model)
to get a solution
Unless something else isn’t working? I haven’t tried to run your code
See here: Getting started with JuMP · JuMP
Could you be a little more precise as to what “not working” means to you? It would make it easier to help
This is not valid Julia syntax, it should be optimize!(model)
. Was that the issue?
Ok, but do you see an error or a wrong result? What do you get? How do you know the true value?
At first glance you still need to specify an optimizer for the code to run
After adding an optimizer and fixing a few syntax mistakes, I get 12 instead of 14. Are you sure about your values?
julia> using JuMP, HiGHS
julia> costs = Dict("A" => [2.0, 2.0, 2.0], "B" => [3.0, 3.0, 3.0],);
julia> capacity = Dict("A" => [2.0, 2.0, 1.0], "B" => [1.0, 2.0, 4.0],);
julia> demand = [2.0, 1.0, 3.0];
julia> function op(capacity, costs, demand, optimizer)
C = keys(capacity)
D = keys(demand)
m1 = Model(optimizer)
@variable(m1, 0 <= x[c in C, d in D])
@objective(m1, Min, sum(costs[c][d] * x[c, d] for c in C, d in D))
@constraint(m1, [d in D], sum(x[c, d] for c in C) >= demand[d])
optimize!(m1)
print(m1)
return m1
end
op (generic function with 1 method)
julia> m1 = op(capacity, costs, demand, HiGHS.Optimizer);
Running HiGHS 1.5.3 [date: 1970-01-01, git hash: 45a127b78]
Copyright (c) 2023 HiGHS under MIT licence terms
Presolving model
3 rows, 6 cols, 6 nonzeros
0 rows, 0 cols, 0 nonzeros
Presolve : Reductions: rows 0(-3); columns 0(-6); elements 0(-6) - Reduced to empty
Solving the original LP from the solution after postsolve
Model status : Optimal
Objective value : 1.2000000000e+01
HiGHS run time : 0.00
Min 3 x[B,1] + 3 x[B,2] + 3 x[B,3] + 2 x[A,1] + 2 x[A,2] + 2 x[A,3]
Subject to
x[B,1] + x[A,1] ≥ 2
x[B,2] + x[A,2] ≥ 1
x[B,3] + x[A,3] ≥ 3
x[B,1] ≥ 0
x[A,1] ≥ 0
x[B,2] ≥ 0
x[A,2] ≥ 0
x[B,3] ≥ 0
x[A,3] ≥ 0
julia> println(termination_status(m1))
OPTIMAL
julia> println(objective_value(m1))
12.0
julia> println(value.(m1[:x]))
2-dimensional DenseAxisArray{Float64,2,...} with index sets:
Dimension 1, ["B", "A"]
Dimension 2, [1, 2, 3]
And data, a 2×3 Matrix{Float64}:
0.0 0.0 0.0
2.0 1.0 3.0
Have you tried running my corrected code? There were a few typos in yours, for instance you did for c in c
whereas you should have separated the key from the key set
The code I gave you runs on my computer, did you change the other bits too?