How to create independent normal distribution variables in JuMP

Hello :smiley:

I followed the previous work to define variables (normal distribution) in JuMP v.1.22.2 and want to use like this:

@indepnormal(m_chance, ω[i=1:numfarms], mean=0, var=farms[i].σ^2)

But I met issues, following is my updated code:

using Random

macro indepnormal(m, x, mean, var)
m = esc(m)
@assert isa(mean, Expr) && mean.head == :(=) && mean.args[1] == :mean
@assert isa(var, Expr) && var.head == :(=) && var.args[1] == :var
mean = esc(mean.args[2])
var = esc(var.args[2])

if isa(x, Symbol)
return quote
$(esc(x)) = IndepNormal($m, $mean, var, (string(x)))
nothing
end
else
if !(isa(x, Expr) && x.head == :ref)
error(“Syntax error: Expected $x to be of form var[…]”)
end

   refcall = x.args[1]
   idxvars = x.args[2:end]
   variable = gensym(refcall)

   idxvars_exprs = Expr[]
   for idxvar in idxvars
       push!(idxvars_exprs, :(for $(esc(idxvar)) in $(esc(refcall).args[2]) end))
   end

   varname = string(refcall)
   varstr = :(string($varname, "["))

   for idxvar in idxvars
       push!(varstr.args, :(string($(esc(idxvar)))))
       push!(varstr.args, ",")
   end
   deleteat!(varstr.args, length(varstr.args))
   push!(varstr.args, "]")

   code = quote
       $(esc(refcall))[$(esc.(idxvars)...)] = IndepNormal($m, $mean, $var, $varstr)
   end

   looped_code = code
   for (idxvar, idxset) in zip(idxvars, idxvars_exprs)
       looped_code = quote
           $idxset
           $looped_code
       end
   end

   return quote
       $looped_code
       $esc(refcall) = $variable
   end

end
end

Now an error shows: **LoadError: LoadError: BoundsError: attempt to access 1-element Vector{Any} at index [2]. I don’t know how to make it work.

Any answer would be very appreciated. :pray:

JuMPChance GitHub - mlubin/JuMPChance.jl: A JuMP extension for probabilistic (chance) constraints is old archived code that does not support JuMP v1.22.

You should’t use it, and the code is probably not helpful to look at. I would strongly warn you against writing a macro; they are non-trivial to get right.

Thank you @odow, I couldn’t agree more after so many days of trying.

Is there any way to add variables that follow a normal distribution in the JuMP model without writing a macro?

You cannot add variables that follow a normal distribution to a JuMP model.

If you want to solve a chance-constrained optimization problem, you will need to manually implement the reformulation.

The macro in JuMPChance was only a small user-facing feature. Most of the effort in the package was to automatically build the reformulations.

1 Like

Thanks a lot @odow, now it’s clear.

1 Like