> I am trying to apply a lot of multivariate derivatives to a complex vector
> and I'm attempting to break apart my answer into sub-expressions to reduce
> the number of terms.
>
> To support this in Sage 7.3, I need to identify subexpressions that can
> be simplified back into my original set of variables.
>
> In this toy example I have a radius variable r, the norm of the vector (x,y,z).
> A simple direct substitution for r works, but it fails when even the simplest
> operations are performed on the variables.
>
> An example follows:
>
Let's look at this example more closely. I'm using the Sage REPL
and avoiding "show" to make things easier to copy and paste.
$ sage -v
SageMath version 7.3, Release Date: 2016-08-04
$ sage -q
sage: x, y, z = SR.var('x y z', domain='real')
sage: r = SR.var('r', domain='positive')
sage: r2 = x^2 + y^2 + z^2
sage: r2.subs(r2 == r^2)
r^2
sage: q = (r2 - 3 * r^2)/ (r^3)
sage: q
-(3*r^2 - x^2 - y^2 - z^2)/r^3
sage: qr = q.subs(r2 == r^2)
sage: qr
-(3*r^2 - x^2 - y^2 - z^2)/r^3
sage: qr.simplify()
-(3*r^2 - x^2 - y^2 - z^2)/r^3
The problem is that subtracting `r2 - 3 * r^2` yields an expression
whose expression tree no longer contains `(x^2 + y^2 + z^2)`. Indeed:
sage: q.operands()
[3*r^2 - x^2 - y^2 - z^2, r^(-3), -1]
sage: a, b, c = q.operands()
sage: a
3*r^2 - x^2 - y^2 - z^2
sage: a.operands()
[3*r^2, -x^2, -y^2, -z^2]
One workaround in this case is as follows:
sage: q1 = q.subs({r^2: r2})
sage: q1
-2*(x^2 + y^2 + z^2)/r^3
sage: q2 = q1.subs({r2: r^2})
sage: q2
-2/r