How to add a constraint with neural network in a JuMP (PowerModels) model


I want to create a constraint: a variable var1 is equal to the output of a torch artificial neural network whose input is another variable var2.

------- This following function is my ann prediction (the ANN has been imported) -----

function get_y_pred(ann, x, x_scl, y_scl) 
# x_scl and y_scl are scaler to modify the input x and output y.
    x_std = x_scl.transform(x)
    x_std = V.Variable(torch.from_numpy(x_std).float())
    y_std = ann(x_std).data.numpy()
    y_pred = y_scl.inverse_transform(y_std)
    return y_pred

The input x should be a matrix containing var2 and some constants, e.g.,

x = [1.0, 0.6, var2, 0.8]  # Vector
x = reshape(x, 1, length(x))  # Vector to Matrix

now I try to add a constraint for var1, i.e., during the optimization var1 should be adaptively changed by the ANN.

@addNLconstraint(model, var1 == get_y_pred(ann, x, x_scl, y_scl))

but it does not work, because I can not create a constraint by using a self-defined function or expression (get_y_pred) with ANN.

Can anyone help me with finding a way to solve this problem? Thank you very much!

Have you tried defining an expression whose value is the output of your get_y_pred function and then using your expression in the NLconstraint?

Hi there, since it’s your first post, please read Please read: make it easier to help you. It’s easier to help if you provide a complete minimal working example.

However, there’s some scary stuff in your example that are going to cause issues.

  • I don’t think your get_y_pred is going to support automatic differentiation. That means you can’t use JuMP to solve this problem. Please read: Should I use JuMP? · JuMP
  • @addNLconstraint is very old syntax. Are you running the latest version of Julia and JuMP?

yes, I tried, it also doesn’t work.
I think, if I use the function get_y_pred, I have to give x a specific matrix, not a matrix containing the JuMP variable var2. Because there is an ANN in the function get_y_pred. Its input has to be actual values.

The x containing var2 is a 1x4 Martix{AffExpr}. The input the function get_y_pred really needs should be a 1x4 Martix{Float64}.

1 Like

Thank you for the suggestions.

1 Like