# Collecting w.r.t. long expression

Sorry for a probably naive question.

I have the following expression

s = a g[1, 1] + a g[1, 2] + a g[1, 3] + a g[2, 3] + a q[1] -
b e g[1, 1] q[1] - d e g[1, 1] q[1] - b e g[1, 2] q[1] -
d e g[1, 2] q[1] - b e g[1, 3] q[1] - d e g[1, 3] q[1] -
b g[1, 4] q[1] - b g[1, 5] q[1] - b e g[2, 3] q[1] -
d e g[2, 3] q[1] - b g[3, 4] q[1] - b g[3, 5] q[1] - b e q[1]^2 -
d e q[1]^2 - b e g[1, 1] q[2] - d e g[1, 1] q[2] -
b e g[1, 2] q[2] - d e g[1, 2] q[2] - b e g[1, 3] q[2] -
d e g[1, 3] q[2] - b g[1, 4] q[2] - b g[1, 5] q[2] -
b e g[2, 3] q[2] - d e g[2, 3] q[2] - b g[3, 4] q[2] -
b g[3, 5] q[2] - b e q[1] q[2] - d e q[1] q[2] - d g[1, 1] q[4] -
d g[1, 2] q[4] - d g[1, 3] q[4] - d g[2, 3] q[4] - d q[1] q[4] -
d g[1, 1] q[5] - d g[1, 2] q[5] - d g[1, 3] q[5] - d g[2, 3] q[5] -
d q[1] q[5];

Let's introduce the symbols

h[1] = g[1, 1] + g[1, 2] + g[1, 3] + g[2, 3] + q[1];
h[2] = g[1, 4] + g[1, 5] + g[3, 4] + g[3, 5];
h[3] = q[1] + q[2];
h[4] = q[4] + q[5];

Then once we consider

f = -b h[2] h[3] + a h[1] - (b e + d e) h[1] h[3] - d h[1] h[4];

we conclude that s=f:

In[244]:= FullSimplify[s - f]
Out[244]= 0

I knew that s should be expressed through h[1],h[2],h[3],h[4] (I didn't know about the form of f as function of those h though).

I got this explicit form of f looking at s and making several Collect operators (w.r.t. -d e, -b e and so on).

My question is whether it is possible to get f without analysing the structure of s, but just ask "Represent s as a polynomial (or a function) of h[1],h[2],h[3],h[4]"?

If you just substitute a few variables it works:

s = a*g[1, 1] + a*g[1, 2] + a*g[1, 3] + a*g[2, 3] + a*q[1] - b*e*g[1, 1]*q[1] -
d*e*g[1, 1]*q[1] - b*e*g[1, 2]*q[1] - d*e*g[1, 2]*q[1] - b*e*g[1, 3]*q[1] -
d*e*g[1, 3]*q[1] - b*g[1, 4]*q[1] - b*g[1, 5]*q[1] - b*e*g[2, 3]*q[1] -
d*e*g[2, 3]*q[1] - b*g[3, 4]*q[1] - b*g[3, 5]*q[1] - b*e*q[1]^2 - d*e*q[1]^2 -
b*e*g[1, 1]*q[2] - d*e*g[1, 1]*q[2] - b*e*g[1, 2]*q[2] - d*e*g[1, 2]*q[2] -
b*e*g[1, 3]*q[2] - d*e*g[1, 3]*q[2] - b*g[1, 4]*q[2] - b*g[1, 5]*q[2] -
b*e*g[2, 3]*q[2] - d*e*g[2, 3]*q[2] - b*g[3, 4]*q[2] - b*g[3, 5]*q[2] -
b*e*q[1]*q[2] - d*e*q[1]*q[2] - d*g[1, 1]*q[4] - d*g[1, 2]*q[4] - d*g[1, 3]*q[4] -
d*g[2, 3]*q[4] - d*q[1]*q[4] - d*g[1, 1]*q[5] - d*g[1, 2]*q[5] - d*g[1, 3]*q[5] -
d*g[2, 3]*q[5] - d*q[1]*q[5];
hs = {h[1] == g[1, 1] + g[1, 2] + g[1, 3] + g[2, 3] + q[1],
h[2] == g[1, 4] + g[1, 5] + g[3, 4] + g[3, 5], h[3] == q[1] + q[2],
h[4] == q[4] + q[5]};
Collect[s /. Solve[hs, {g[1, 1], g[1, 4], q[1], q[4]}][[1]], _h, Factor]

gives

(-b)*h[2]*h[3] + h[1]*(a - (b + d)*e*h[3] - d*h[4])