Skip to content

Symbolic improvements

Daniel Brown requested to merge fix/symbol_parameterref into develop

What does this MR do and why?

  • Fixes equality comparisons between symbolic objects

  • Fixes Symbol.lambdify and adds tests

  • fix tests so that reference to model isn't lost randomly half way through

  • stop using weakref for parameterref as you can end up with a segfault when the model is garbage collected and referencing symbols are still around. Evaluating such elements when the Model has been GC'd will result in a normal python error now, not a segfault.

  • Adds a new substitute method to the symbols for replacing terms and not evaluating anything. This was causing issues as eval(subs) also evaluates ParameterRef objects to the current parameter value, which is not what is needed in some cases, such as making symbolic expressions including changing parameters for cythonising. This commit also properly tests parameterref objects the same as Variables now.

Examples of different behaviour

Originally this would result in:

(a+b).eval(subs={a:b, b:1}) -> 1+b

whereas you'd expect (and this MR now makes it do)

(a+b).eval(subs={a:b, b:1}) -> b+b = 2

The eval method did a bit of both substituting and evaluating parameter references to the current parameter value. substitute has now been added for just doing subbing and no evaluation.

This MR changes the behaviour of substitution too. It is no longer recursive, for example this will be the result now:

y = a+b
y.substitute({a:a+b, b:a} -> a+b -> (a+b) + b -> (a+b) + a -> a+b+a

Continuously applying substitutions can lead to infinite loops at times and depending on the ordering of the mappings applied can be confusing, so they are only applied to the top level expression. The user can just continuously apply substitute if needed until the result doesn't change. Maybe this could be an option but I don't see the need currently.

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

  • Includes tests for added/modified code
  • Added or modified the documentation if relevant
  • Docstrings added/modified for new/modified functions
  • Committer/reviewer has ran the documentation stage when ready to merge
Edited by Daniel Brown

Merge request reports