dirkschumacher / ompr

R package to model Mixed Integer Linear Programs
https://dirkschumacher.github.io/ompr/
Other
268 stars 35 forks source link

ompr::add_constraint(.): Adding a simple char-constraint (?), ERROR: The expression contains a variable that is not part of the model #337

Closed Martin-Grub closed 2 years ago

Martin-Grub commented 3 years ago

Dear community! Does anybody know, how to add a simple string as a constraint to a model? After some trying, I found that the following IS working: ompr::add_constraint(model, sum_expr(str2lang("10 x[1,1] + 10 x[2,1]"), i=1:1) <= 1000).

Unfortunately, it is NOT working, when I pack the string into a var strTmp <- "10 x[1,1] + 10 x[2,1]". With this in mind: ompr::add_constraint(model, sum_expr(str2lang(strTmp ), i=1:1) <= 1000) I get an ERROR: Error in check_for_unknown_vars_impl(model, the_ast) : The expression contains a variable that is not part of the model.

I am looking for a way to resolve some externally generated strings, that formulate some linear inequations with registered model vars (x[i,j]).

Does anyone has an idea? Thanks a lot in advance!

dirkschumacher commented 3 years ago

Hey, this will not work due to how ompr was written. You could try something like this (untested):

strTmp <- "10 * x[1,1] + 10 * x[2,1]"
eval(bquote(ompr::add_constraint(model, sum_expr(.(str2lang(strTmp)), i=1:1) <= 1000)))
Martin-Grub commented 3 years ago

Thank you, Dirk, for your answer! Unfortunately, this still seems not to be the solution. Executing your suggestion gives an answer:

Mixed integer linear optimization problem Variables: Continuous: 1960 Integer: 0 Binary: 0 Model sense: minimize Constraints: 1

Everything looks good, but when looking into the model, it turns out, that there is a list of 0 constraints, not 1. Repeating does not help. The answer ist 1 constraint, the result is 0 constraints.

Do you have any idea??

Kind regards, Martin