Use or not functions in JuMP

Hey, guys.
This is my first time working with both Julia and JuMP. It has been an adventure (and a lot of mistakes).
Right now I accomplished to do the base code to work as I need and I am trying to put it inside the JuMP format, but I am having some problems.
First of all, I need to do a lot of calculations using my variable (called DELTA) so I can get the calculation of what I need to minimize with the objetive.
My first question is: Do I need to put this operations inside a function or I can do just like the example below?

@variable(model, DELTA[1:length(CITIES_ID)], Bin)

DN = []
VALUE = []
for i in 1:QTD_PATHS
    for i in 1:size(DEMANDS,2)
        op_mult = DEMANDS[i]*DELTA[i]
        push!(DEMANDS_OTIM, op_mult)

    for j in 1:size(PATHS_NUM,2)
        for i in 1:size(PATHS_NUM,1)
            subst = PATHS_OTIM[findfirst(isequal(PATHS_NUM[i,j]),CITIES_ID)]
    MATRIX_PATHS = reshape(MATRIX_PATHS, size(PATHS_NUM,1), size(PATHS_NUM,2))

    for i in 1:size(FLOW_PATHS,2)
        diam = 0.8 * ((FLOW_PATHS[i])/1000)^(1/2)) * 1000
        if diam < 100
            diam_nominal1 = 75
            push!(DN, diam_nominal1)
        elseif 100 <= diam <= 400
            diam_nominal1 = 50 * div(diam, 50, RoundDown)
            vel1 = FLOW_PATHS[i]/(diam_nominal1)
            push!(DN, diam_nominal1)
        elseif diam > 400
            diam_nominal1 = 100 * div(diam, 100, RoundDown)
            push!(DN, diam_nominal1)

for i in 1:length(DN)
    custos = lista_custos[findfirst(isequal(DN[i]),lista_diam)] * LENGTH[i]
    VALUE = vcat(VALUE, custos)

for i in 1:length(QTD_SUBPATHS)
    value_path = sum(VALUE[SUBPATH[i,1]:SUBPATH[i,2]])
    VALUE_PATH = vcat(VALUE_PATH, value_path)

@constraint (model, DELTA[3]+DELTA[20]=1)
@constraint (model, DELTA[1]=1)
@objective (model, Min, VALUE_PATH[i] for i in 1:QTD_PATHS)
otimizacao = optimize!(transpModel)

This is just an example, just a bit of the code. I am working with excel data, so I don’t know if it would be helpful paste the entire code.

Hi @lara, welcome!

Do I need to put this operations inside a function or I can do just like the example below?

A great read, if you haven’t already, is Performance Tips · The Julia Language.

The first two points are:

Since this setup code isn’t performance sensitive, if it works, then you can leave it as the example.

In general though, you’ll benefit from creating a function because it’s a better software engineering practice. You can test that it returns the right outputs for a given input, you can move it somewhere else as a single blob, and it removes the dependence global variables.

1 Like