How to solve a degenerate system of equations in sympy

Viewed 463

I have lots of systems of equations, some are underspecified, and I would like to find one non-zero solution if it exists or report that there are none. However, sympy seems to hang trying to find all solutions. Here is an extreme example.

from sympy import *
A = Matrix([
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
])
syms = symbols("x:12")
s = Matrix(syms)
constraints = [xi**3 - xi for xi in syms]
solve(list(A*s) + constraints, syms)

How can I get sympy to just report one non-zero solution quickly in an example like this? In fact I would be happy if it just reported that there was a solution.

1 Answers

Give SymPy increasingly harder systems (with fewer specified 0s) and quit when you get a solution:

>>> def nonzsol(eqs, syms):
...     from sympy import subsets
...     for i in range(len(syms)-1,-1,-1):
...         for z in subsets(syms, i):
...             s, nontriv = solve(eqs + list(z), set=True)
...             for v in nontriv:
...                 if any(v):
...                     return dict(zip(s, v))
... 
>>> 
>>> nonzsol(eqs, syms)
{x0: 0, x1: 0, x10: 0, x11: -1, x2: 0, x3: 0, x4: 0, x5: 0, x6: 0, x7: 0, x8: 0, x9: 0}
Related