Extracting Coefficients of Multivariate Polynomial


(Patham9) #1

I have an expression like

“(-2) + (-1)^2 + 0^2 + 1^2 + 0u0_0_0 + u0_0_0^2 + 0u1_0_0 + (-2)1^2u1_0_0 + 21^2u1_0_0 + (-2)u0_0_0u1_0_0 + (-1)^2u1_0_0^2 + 1^4u1_0_0^2”

How can I let it kick out the unnecessary summands like 0^2, and how can I let it combine the coefficients so that instead of ab + cb there will just be (a+c)*b, and finally obtain the coefficient (a+c) for the variable b?
I tried to use Polynomial.Coefficients, Polynomial.Coefficient but these function didn’t do what I expected from such functions to do, namely returning the coefficients for the different symbolic terms in the polynomial expression.

Best regards,
Patrick


(Patham9) #2

Ok I found a solution, for the case someone else also needs it:

var collected_summands = new HashSet();
var symbols = Structure.CollectIdentifiers(multivariate_poly);
var summands = Algebraic.Summands(multivariate_poly);
double offset = 0.0;
Dictionary<Expr, Expr> factors = new Dictionary<Expr, Expr>();
foreach (var summand in summands)
{
if (Structure.CollectIdentifiers(summand).IsEmpty) //there is no symbol so its just a value
{
offset += MathNet.Symbolics.Evaluate.Evaluate(new Dictionary<string, FloatingPoint>(), summand).RealValue;
}
}
foreach (var symbol in symbols)
{
foreach (var summand in summands)
{
var identifiers = Structure.CollectIdentifiers(summand);
if (identifiers.Contains(symbol) && !collected_summands.Contains(summand)) //only these summands that contain the variable interest us
{
collected_summands.Add(summand); //commenting this line out will lead to factors[a]=b and factors[b]=a for a summand a*b instead of just one of them added to factors.
if (factors.ContainsKey(symbol)) //we already have a factor? then add the new one divided by the factor we are looking at
{
factors[symbol] = factors[symbol] + (summand / symbol);
}
else //else we just add the new factor
{
factors[symbol] = (summand / symbol);
}
}
}
}

//testing it:
Expr reconstruct_poly = Expr.Real(offset);
foreach (var symbol in symbols)
{
reconstruct_poly += symbol * factors[symbol];
}
Expr check = Rational.Simplify("", multivariate_poly - reconstruct_poly);
if (MathNet.Symbolics.Evaluate.Evaluate(new Dictionary<string, FloatingPoint>(), check).RealValue != 0)
{
throw new Exception(“reconstruction by factors not equal with the polynomial we extracted a factor-interpretation from.”);
}

Best regards,
Patrick