Macro to substitute parameters used for JuMP model

I read available topics on macros but still can not make working macro to substitute parameter. What I want is instead of creating new variable (for example Pmax) to use @Pmax macro that will expand @Pmax(g) to data[:gen][g][“pmax”].

My goal is to avoid performance penalty of copying data parameter to new parameters (just like Pmax) just to make model definition shorter. Sample code that I would like recoded with macro is provided below.

using JuMP, PowerModels

function OPF(file)

     data = build_ref(parse_file(file))[:it][:pm][:nw][0]

     G = keys(data[:gen])
     Pmin = Dict(g=>data[:gen][g]["pmin"] for g in G)
     Pmax = Dict(g=>data[:gen][g]["pmax"] for g in G)
     #more parameters come here

     pol = Model(Ipopt.Optimizer)

     @variable(pol,Pgen[g in G])
     #more variables come here
     Pmin = Dict(g=>data[:gen][g]["pmin"] for g in G)
     Pmax = Dict(g=>data[:gen][g]["pmax"] for g in G)

     @constraint(pol,pg12[g in G], Pmin[g] <= Pgen[g] <= Pmax[g] )
     #more constraints come here

    return optimize!(pol)
end

As a user, you should never* write your own macro. There is always a simpler and easier way to achieve what you are trying to do.

For example, you could use a function:

using JuMP, PowerModels
function OPF(file)
    data = build_ref(parse_file(file))[:it][:pm][:nw][0]
    G = keys(data[:gen])
    Pmin(g) = data[:gen][g]["pmin"]
    Pmax(g) = data[:gen][g]["pmax"]
    model = Model(Ipopt.Optimizer)
    @variable(model, Pmin(g) <= Pgen[g in G] <= Pmax(g))
    optimize!(model)
    return
end

*with very few exceptions, which do not apply here.

1 Like

Thanks. It works. I notice no penalty due to using functions.

1 Like