The sort key seems insufficient for sorting unevaluated expressions.
In [37]: Add(x, Mul(x,x,x,evaluate=False), x, evaluate=False)
Out[37]: x + x⋅x⋅x + x
With a slight change, it works as expected:
In [38]: Add(x, Mul(x,y,x,evaluate=False), x, evaluate=False)
Out[38]: x⋅x⋅y + x + x
It seems that the sort key is the same for all three terms in the case that doesn't work.
In [43]: poly=Add(x, Mul(x,x,x,evaluate=False), x, x, evaluate=False)
In [49]: terms, gens = poly.as_terms()
In [56]: key, reverse = poly._parse_order(None)
In [57]: key(terms[0])
Out[57]: ((-1,), (), ((False, 0.0), (1.0, 0.0)))
In [58]: key(terms[1])
Out[58]: ((-1,), (), ((False, 0.0), (1.0, 0.0)))
In [59]: key(terms[2])
Out[59]: ((-1,), (), ((False, 0.0), (1.0, 0.0)))
Since the key function completely ignores the first component of each term, I'm guessing that the remaining components of the term data structure all supposed to encode all the useful information. Except for the first component, each term is identical, which I believe to be the source of the problem.
In [68]: terms[0]
Out[68]: (x, ((1.0, 0.0), (1, 0), ()))
In [69]: terms[1]
Out[69]: (x⋅x⋅x, ((1.0, 0.0), (1, 0), ()))
In [70]: terms[2]
Out[70]: (x, ((1.0, 0.0), (1, 0), ()))
I can't say I understand all the ways in which terms are used, so I don't know what would be an appropriate fix. But, clearly, it's broken for the terms one gets with unevaluated functions.
Any idea on how to fix it?
Duane