Welcome to Cadabra Q&A, where you can ask questions and receive answers from other members of the community.
+1 vote

There is an interesting bug (?) when one manually fiddles with the multiplier on \sum.

ex := x+y;
ex.top().multiplier=-1

display(ex) and ex.input_form both return x+y. But if I access @(ex), it returns -x-y. tree(ex) clearly sees the -1 on the \sum node.

Presumably the multiplier on sum shouldn't be manually modified by the user, but I found this behaviour interesting.

in Bug reports by (1.0k points)

1 Answer

+1 vote

If you modify the tree, you are required to leave the tree in an internally consistent state. One of the conditions is that the multiplier of a \sum node is not allowed to be anything except 1.

On the C++ side there are various functions in Cleanup.cc|hh which help to turn an inconsistent tree into a consistent one, but these are not exported to Python. It should not be too hard to export these as it's all individual functions.

The reason why ex2:=@(ex) works is that any new expression input will run the cleanup routines.

(In all honesty, apart from Dom, you are the first person I am aware of who has done some serious work like this on the Python side, so there are bound to be other missing pieces).

by (82.6k points)

Ah, makes sense.

I ran into this because I was trying to do something tricksy with directly calling .replace() on an ExNode.

For example, here is a low-brow attempt to replace x -> a+b at the top level in a sum manually.

ex := 3 x + 3x*z;
for term in ex.top().terms():
    for factor in term.factors():
        if ( factor.name == "x" ):
            factor.replace(Ex('a+b'))
ex;

This fails on the first term because the 3 is a multiplier directly on the x node, so my clever idea was to add some code to catch the multiplier and append it it to the sum, but that leads to the above-mentioned issue.

For anyone reading this, one of the cleanup functions Kasper mentioned is available as ex.cleanup() and solves the problem I mentioned.

We need better documentation, clearly.

...