chocoteam / choco-solver

An open-source Java library for Constraint Programming
http://choco-solver.org/
BSD 4-Clause "Original" or "Old" License
687 stars 137 forks source link

Make possible to rewrite discrete expressions with rules #983

Open cprudhom opened 1 year ago

cprudhom commented 1 year ago

This pull request address makes it possible to define rewriting rules to transform an expression. One has to define one or more couples, each composed of a predicate (to detect a pattern) and a function (to transform the expression detected). Then a call to e.rewrite(...) transform in-place the expression.

I also (started to) define some pre-defined predicates and functions, like Rule.isOperator(...) and Rule.twoIdentical(...).

Basic example:

Model model = new Model("rewrite1");                                       
IntVar x = model.intVar("x", 0, 10);                                       
IntVar y = model.intVar("y", 0, 10);                                       

List<Rule<ArExpression>> rules = new ArrayList<>();                        
rules.add(new Rule<>(                                                      
        Rule.isOperator(ArExpression.Operator.ADD),                        
        Rule.twoIdentical(e -> e.mul(2))));                                
rules.add(new Rule<>(                                                      
        Rule.isOperator(ArExpression.Operator.SUB),                        
        Rule.twoIdentical(e -> model.intVar(0))));                         

ReExpression exp = x.add(x).eq(y.sub(y)).rewrite(rules);                                  
System.out.printf("%s\n", exp);                                            

Related to: #979 #953 @arnaud-m if you want to play with the branch, you're welcome, this is a draft PR, waiting for feedbacks.