Search code examples
juliajulia-jump

Is it possible reduce time of building a mathematical formulate in coding?


I would like to use the optimization model in a code. But processing and preparation time of the objective function (f) is too long. Is there any way to reduce the time of these kinds of large models?

using JuMP,CPLEX
Tsp=Model(solver=CplexSolver());

#Parameters-----------------------------------------------------------------
V, T, K = 1:100, 1:5, 1:5
totalV=100
d=1 .+ 99 .*rand(V,V);
#variables---------------------------------------------------------------------
@variable(Tsp,x[V,V,K,T],Bin);

@variable(Tsp,u[V,V,K,T]>=0);
#constrains---------------------------------------------------------------------
@constraint(Tsp,c1[i in V, k in K,t in T ], sum(x[i,j,k,t] for j in V )==1);

@constraint(Tsp,c2[j in V, k in K,t in T], sum(x[i,j,k,t] for i in V )==1);

@constraint(Tsp,c3[i in U,j in V,k in K, t in T; i!=j],u[i,k,t]-u[j,k,t]+totalV*x[i,j,k,t]<=totalV-1);
# objective function---------------------------------------------------------
f=sum(d[i,j]*x[i,j,k,t] for i in V,j in V, k in K, t in T);

@objective(Tsp, Min, f);

solve(Tsp);

Thanks very much.


Solution

  • I'll assume you're using JuMP due to the tag.

    1. Always provide a reproducible example: https://stackoverflow.com/help/minimal-reproducible-example. It's hard to offer advice without it.
    2. Do not build JuMP expressions outside of the macros: https://jump.dev/JuMP.jl/stable/tutorials/getting_started/performance_tips/#Use-macros-to-build-expressions
    3. Your code is wrong. If V = 100, then for i in V will only have one element, and that is i = 100. Perhaps you meant for i in 1:V?
    4. Think about what the if statement is doing. It only uses i and j, but it needs to be evaluated for every t and every k.

    Putting it all together, I would do something like:

    V, H, K = 1:100, 1:5, 1:5
    using JuMP
    model = Model()
    @variable(model, x[V, V, K, H])
    d = 1 .+ 99 .* rand(V, V)
    @expression(
        model, 
        f, 
        sum(d[i, j] * sum(x[i,j,k,t] for t in H, k in K) for for i in V, j in V if i!=j)
    )
    

    Hope that helps.