Substitution of products of symbolic variables

I am trying to simplify a symbolic expression by replacing products of symbolic variables, eg. x*y, with a single new variable, e.g. z, but I cannot succeed in doing it. Any suggestion?


using Symbolics
using SymbolicUtils

@variables x[1:2] z

f = 3.0 + 2.0*(x[1]*x[2]);
g = substitute(f, Dict(x[1]*x[2] => z));


Actual output: 3.0 + 2.0x[1]*x[2]
Expected output: 3.0 + 2.0z


using SymbolicUtils

@syms a b z

r = @acrule *(a, b) => z
f = 3.0 + 2.0b*a
simplify(f, RuleSet([r]))

Thank you.
Is this extensible to arrays of symbolic variables someway?

Ideally, I have a complex expression (a polynomial in the x[i], where x is an array of symbolic variables and the coefficients can be either floats or other symbolic variables) and a list of “monomials” that I want to replace, e.g. c*x[1]*x[2] => c*y[1], d*x[1]^2 => d*y[2], etc…

The goal is:

  • set to zero all monomials of order greater than 2, e.g. x[1]^3 or x[1]*x[2]*x[3]
  • replace all second-order expressions with a simpler one, e.g. c*x[1]^2 => c*y[1] or d*x[1]*x[2] => d*y[2]

Write down all the rules and interpolate when you refer to an array element.
r = [@acrule(*($(x[1]), $(x[2]), $(x[3])) => 0)]
If you work with polynomials the polynomial_coeffs function may be useful.
d, rem = polynomial_coeffs(f, [x...])