Simplify a nonlinear expression

Hi,

Is there any way we can simplify a nonlinear expression automatically in JuMP. For example, if we have:

using JuMP, MadNLP
model = Model(MadNLP.Optimizer)
@variable(model, CA)
@variable(model, CB)
expr_str = :($(CA) + $(CA) + $(CB))
expr_NL = add_nonlinear_expression(model, expr_str)

Is it possible for JuMP to automatically convert expr_str to :(2*$(CA) + $(CB)) instead of :($(CA) + $(CA) + $(CB))? Thanks for your help!

Is it possible for JuMP to automatically convert

Nope. We use the expressions you pass as-is.

Although the new nonlinear rewrite that is in progress, https://github.com/jump-dev/JuMP.jl/pull/3106, will automatically detect linear and quadratic expressions and simplify them.

Thanks for the answer. Will the rewrite able to simplify linear/quadratic expressions which are parts of a larger nonlinear expression? For example, x + exp(x + x + x*y) + x to 2*x + exp(2*x + x*y). :grinning:

Will the rewrite able to simplify linear/quadratic expressions which are parts of a larger nonlinear expression?

Mostly. But there are a few cases where we won’t:

julia> using JuMP

julia> model = Model();

julia> @variable(model, x);

julia> @variable(model, y);

julia> @expression(model, x + exp(x + x + x*y) + x)
+(x, exp(x*y + 2 x), x)

julia> @expression(model, x + x + exp(x + x + x*y))
+(2 x, exp(x*y + 2 x))

Because we build expressions from left to right, the first @expression doesn’t go back and realize that it could add the first and third terms together.

1 Like

It might be worth giving MTK a try Modeling Optimization Problems · ModelingToolkit.jl if you have such expressions in constraints, then you can call structural_simplify on the OptimizationSystem though it doesn’t do it for the objective right now

Fantastic. I am looking forward to the feature’s release. Thanks for the great work!

Thanks for the suggestion. But I do not have such expressions in constraints or the objective function. They are some expressions that I would like to calculate their values at the optimal conditions.