o
    Rh j                     @  s  d Z ddlmZ ddlmZ ddlmZmZ ddlZddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZ ddlmZ ddlmZ ddlmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z- ddlm.Z.m/Z/ ddl0m1Z1 G dd de2Z3ddddZ4dd Z5dLdd Z6d!d" Z7dMdNd,d-Z8dOd1d2Z9dMdPd4d5Z:dMdNd6d7Z;dQd9d:Z<dRd<d=Z=dSd@dAZ>dSdBdCZ?dTdFdGZ@dHdI ZAdJdK ZBdS )Uz,Solvers of systems of polynomial equations.     )annotations)Any)SequenceIterableN)Dummy)S)Expr)factor_terms)default_sort_key)Boolean)Polygroebnerroots)ZZ)build_options)parallel_poly_from_exprsqf_part)ComputationFailedPolificationFailedCoercionFailedGeneratorsNeededDomainErrorrcollect)	postfixes)cartes)
filldedent)OrAndEqc                   @  s   e Zd ZdZdS )SolveFailedz.Raised when solver's conditions were not met. N)__name__
__module____qualname____doc__ r&   r&   W/home/air/sanwanet/backup_V2/venv/lib/python3.10/site-packages/sympy/solvers/polysys.pyr!   #   s    r!   Fstrictc          	   
   O  s   zt | g|R i |\}}W n ty# } ztdt| |d}~ww t|t|j  kr3dkrYn n$|\}}tdd | |  D rYzt|||W S  tyX   Y nw t	|||dS )a  
    Return a list of solutions for the system of polynomial equations
    or else None.

    Parameters
    ==========

    seq: a list/tuple/set
        Listing all the equations that are needed to be solved
    gens: generators
        generators of the equations in seq for which we want the
        solutions
    strict: a boolean (default is False)
        if strict is True, NotImplementedError will be raised if
        the solution is known to be incomplete (which can occur if
        not all solutions are expressible in radicals)
    args: Keyword arguments
        Special options for solving the equations.


    Returns
    =======

    List[Tuple]
        a list of tuples with elements being solutions for the
        symbols in the order they were passed as gens
    None
        None is returned when the computed basis contains only the ground.

    Examples
    ========

    >>> from sympy import solve_poly_system
    >>> from sympy.abc import x, y

    >>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y)
    [(0, 0), (2, -sqrt(2)), (2, sqrt(2))]

    >>> solve_poly_system([x**5 - x + y**3, y**2 - 1], x, y, strict=True)
    Traceback (most recent call last):
    ...
    UnsolvableFactorError

    solve_poly_systemN   c                 s  s    | ]}|d kV  qdS )r+   Nr&   ).0ir&   r&   r'   	<genexpr>\       z$solve_poly_system.<locals>.<genexpr>r(   )
r   r   r   lengensalldegree_listsolve_biquadraticr!   solve_generic)	seqr)   r1   argspolysoptexcfgr&   r&   r'   r*   '   s   -"r*   c           
        s   t | |g}t|dkr|d jrdS t|dkrt|j\} |\}}||js,tt||dd} fddt| D }|	d	}t
t| } fd
dt||D }	t|	tdS )a  Solve a system of two bivariate quadratic polynomial equations.

    Parameters
    ==========

    f: a single Expr or Poly
        First equation
    g: a single Expr or Poly
        Second Equation
    opt: an Options object
        For specifying keyword arguments and generators

    Returns
    =======

    List[Tuple]
        a list of tuples with elements being solutions for the
        symbols in the order they were passed as gens
    None
        None is returned when the computed basis contains only the ground.

    Examples
    ========

    >>> from sympy import Options, Poly
    >>> from sympy.abc import x, y
    >>> from sympy.solvers.polysys import solve_biquadratic
    >>> NewOption = Options((x, y), {'domain': 'ZZ'})

    >>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ')
    >>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ')
    >>> solve_biquadratic(a, b, NewOption)
    [(1/3, 3), (41/27, 11/9)]

    >>> a = Poly(y + x**2 - 3, y, x, domain='ZZ')
    >>> b = Poly(-y + x - 4, y, x, domain='ZZ')
    >>> solve_biquadratic(a, b, NewOption)
    [(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 +       sqrt(29)/2)]
       r   Nr+   F)expandc                   s   g | ]}t | qS r&   r   )r,   expryr&   r'   
<listcomp>       z%solve_biquadratic.<locals>.<listcomp>c                   s    g | ]\}}|  ||fqS r&   )subs)r,   q_rootp_rootr@   r&   r'   rB      s     key)r   r0   	is_groundr!   r1   gcdr   r   keysltrimlist	itertoolsproductsortedr
   )
r;   r<   r9   Gxpqp_rootsq_roots	solutionsr&   r@   r'   r4   e   s"   )



r4   c                   sd   dd  dd d fdd	z
| |j dd	}W n	 ty%   tw |d
ur0t|tdS d
S )a  
    Solve a generic system of polynomial equations.

    Returns all possible solutions over C[x_1, x_2, ..., x_m] of a
    set F = { f_1, f_2, ..., f_n } of polynomial equations, using
    Groebner basis approach. For now only zero-dimensional systems
    are supported, which means F can have at most a finite number
    of solutions. If the basis contains only the ground, None is
    returned.

    The algorithm works by the fact that, supposing G is the basis
    of F with respect to an elimination order (here lexicographic
    order is used), G and F generate the same ideal, they have the
    same set of solutions. By the elimination property, if G is a
    reduced, zero-dimensional Groebner basis, then there exists an
    univariate polynomial in G (in its last variable). This can be
    solved by computing its roots. Substituting all computed roots
    for the last (eliminated) variable in other elements of G, new
    polynomial system is generated. Applying the above procedure
    recursively, a finite number of solutions can be found.

    The ability of finding all solutions by this procedure depends
    on the root finding algorithms. If no solutions were found, it
    means only that roots() failed, but the system is solvable. To
    overcome this difficulty use numerical algorithms instead.

    Parameters
    ==========

    polys: a list/tuple/set
        Listing all the polynomial equations that are needed to be solved
    opt: an Options object
        For specifying keyword arguments and generators
    strict: a boolean
        If strict is True, NotImplementedError will be raised if the solution
        is known to be incomplete

    Returns
    =======

    List[Tuple]
        a list of tuples with elements being solutions for the
        symbols in the order they were passed as gens
    None
        None is returned when the computed basis contains only the ground.

    References
    ==========

    .. [Buchberger01] B. Buchberger, Groebner Bases: A Short
    Introduction for Systems Theorists, In: R. Moreno-Diaz,
    B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01,
    February, 2001

    .. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties
    and Algorithms, Springer, Second Edition, 1997, pp. 112

    Raises
    ========

    NotImplementedError
        If the system is not zero-dimensional (does not have a finite
        number of solutions)

    UnsolvableFactorError
        If ``strict`` is True and not all solution components are
        expressible in radicals

    Examples
    ========

    >>> from sympy import Poly, Options
    >>> from sympy.solvers.polysys import solve_generic
    >>> from sympy.abc import x, y
    >>> NewOption = Options((x, y), {'domain': 'ZZ'})

    >>> a = Poly(x - y + 5, x, y, domain='ZZ')
    >>> b = Poly(x + y - 3, x, y, domain='ZZ')
    >>> solve_generic([a, b], NewOption)
    [(-1, 4)]

    >>> a = Poly(x - 2*y + 5, x, y, domain='ZZ')
    >>> b = Poly(2*x - y - 3, x, y, domain='ZZ')
    >>> solve_generic([a, b], NewOption)
    [(11/3, 13/3)]

    >>> a = Poly(x**2 + y, x, y, domain='ZZ')
    >>> b = Poly(x + y*4, x, y, domain='ZZ')
    >>> solve_generic([a, b], NewOption)
    [(0, 0), (1/4, -1/16)]

    >>> a = Poly(x**5 - x + y**3, x, y, domain='ZZ')
    >>> b = Poly(y**2 - 1, x, y, domain='ZZ')
    >>> solve_generic([a, b], NewOption, strict=True)
    Traceback (most recent call last):
    ...
    UnsolvableFactorError

    c                 S  s(   |   D ]}t|dd r dS qdS )z8Returns True if 'f' is univariate in its last variable. NrD   FT)monomsany)r;   monomr&   r&   r'   _is_univariate  s
   z%solve_generic.<locals>._is_univariatec                 S  s,   |  ||i}| |dkr|jdd}|S )z:Replace generator with a root so that the result is nice. r+   F)deep)as_exprdegreer>   )r;   genzerorT   r&   r&   r'   
_subs_root  s   z!solve_generic.<locals>._subs_rootFc                   s  t | t |  krdkr&n ntt| d |d d }dd |D S t| |dd}t |dkr>|d jr>|s<g S d	S tt |}t |t |k rSttd
t |dkr^|	 }nttd
|j
}|d }tt||d }|s|g S t |dkrdd |D S g }|D ]3}	g }
|d	d }|d	d D ]}|||	}|tjur|
| q|
|D ]
}|||	f  qq|rt |d t |krttd
|S )z/Recursively solves reduced polynomial systems. r=   r   rD   r(   c                 S     g | ]}|fqS r&   r&   r,   ra   r&   r&   r'   rB   #      z@solve_generic.<locals>._solve_reduced_system.<locals>.<listcomp>Tr8   Nzv
                only zero-dimensional systems supported
                (finite number of solutions)
                c                 S  rc   r&   r&   rd   r&   r&   r'   rB   H  re   )r0   rN   r   rL   r   rJ   filterNotImplementedErrorr   popr1   rM   r   Zeroappend)systemr1   entryzerosbasis
univariater;   r`   rX   ra   
new_systemnew_gensbeqsolutionr\   _solve_reduced_systemrb   r)   r&   r'   rw     sH    


z,solve_generic.<locals>._solve_reduced_systemT)rm   NrH   F)r1   r   rh   rQ   r
   )r8   r9   r)   resultr&   rv   r'   r5      s   d	Cr5   c                   s  t ||}t| |dd}tt|}|dd}|rdd }n|d}|dur8t|D ]\}}	|	|||< q,d	d }|d
 d|dd }
}|
  ||
}|r^ fdd|D }n	 fdd|D }t|dd }t	|dd }t
||D ]z\}}t }|D ]n\} g tt
||}}|D ]6}	|f| }|	j| r|	|d
kr|r|	|	j }	|	|t|}|	|| kr|| qt|dd d}||}|D ]}| vr |}n }||f| |f qq|}q|tdd |D tdS )aB  
    Solve a polynomial system using Gianni-Kalkbrenner algorithm.

    The algorithm proceeds by computing one Groebner basis in the ground
    domain and then by iteratively computing polynomial factorizations in
    appropriately constructed algebraic extensions of the ground domain.

    Parameters
    ==========

    polys: a list/tuple/set
        Listing all the equations that are needed to be solved
    gens: generators
        generators of the equations in polys for which we want the
        solutions
    args: Keyword arguments
        Special options for solving the equations

    Returns
    =======

    List[Tuple]
        A List of tuples. Solutions for symbols that satisfy the
        equations listed in polys

    Examples
    ========

    >>> from sympy import solve_triangulated
    >>> from sympy.abc import x, y, z

    >>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1]

    >>> solve_triangulated(F, x, y, z)
    [(0, 0, 1), (0, 1, 0), (1, 0, 0)]

    Using extension for algebraic solutions.

    >>> solve_triangulated(F, x, y, z, extension=True) #doctest: +NORMALIZE_WHITESPACE
    [(0, 0, 1), (0, 1, 0), (1, 0, 0),
     (CRootOf(x**2 + 2*x - 1, 0), CRootOf(x**2 + 2*x - 1, 0), CRootOf(x**2 + 2*x - 1, 0)),
     (CRootOf(x**2 + 2*x - 1, 1), CRootOf(x**2 + 2*x - 1, 1), CRootOf(x**2 + 2*x - 1, 1))]

    References
    ==========

    1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of
    Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra,
    Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989

    Trf   	extensionFc                 S  s   dd | j dddD S )Nc                 S     g | ]\}}|qS r&   r&   )r,   r_r&   r&   r'   rB         zAsolve_triangulated.<locals>._solve_univariate.<locals>.<listcomp>F)multipleradicals)	all_rootsr;   r&   r&   r'   _solve_univariate  s   z-solve_triangulated.<locals>._solve_univariatedomainNc                 S  s   t |   S N)rN   ground_rootsrL   r   r&   r&   r'   r     s   r   rD   r=   c                   s   h | ]
}|f  |fqS r&   )algebraic_fieldrd   domr&   r'   	<setcomp>  s    z%solve_triangulated.<locals>.<setcomp>c                   s   h | ]}|f fqS r&   r&   rd   r   r&   r'   r     rC   c                 S  s   |   S r   )r_   )hr&   r&   r'   <lambda>  s    z$solve_triangulated.<locals>.<lambda>rH   c                 s  s    | ]\}}|V  qd S r   r&   )r,   sr}   r&   r&   r'   r.     r/   z%solve_triangulated.<locals>.<genexpr>)r   r   rN   reversedget	enumerate
set_domainrM   
get_domainr   zipsethas_only_gensr_   r   unifyevaldictrk   minr   addrQ   r
   )r8   r1   r7   r9   rR   rz   r   r   r-   r<   r;   rn   rX   var_seqvars_seqvarvars
_solutionsvaluesHmapping_varsr   rT   ra   dom_zeror&   r   r'   solve_triangulatedi  sT   
4



r   r&   eqsSequence[Expr | complex]r1   Sequence[Expr]kwargsr   returnlist[list[Expr]]c                 K  s2   t | |fi |}dd |D }dd |D }|S )ak	  
    Factorizes a system of polynomial equations into
    irreducible subsystems.

    Parameters
    ==========

    eqs : list
        List of expressions to be factored.
        Each expression is assumed to be equal to zero.

    gens : list, optional
        Generator(s) of the polynomial ring.
        If not provided, all free symbols will be used.

    **kwargs : dict, optional
        Same optional arguments taken by ``factor``

    Returns
    =======

    list[list[Expr]]
        A list of lists of expressions, where each sublist represents
        an irreducible subsystem. When solved, each subsystem gives
        one component of the solution. Only generic solutions are
        returned (cases not requiring parameters to be zero).

    Examples
    ========

    >>> from sympy.solvers.polysys import factor_system, factor_system_cond
    >>> from sympy.abc import x, y, a, b, c

    A simple system with multiple solutions:

    >>> factor_system([x**2 - 1, y - 1])
    [[x + 1, y - 1], [x - 1, y - 1]]

    A system with no solution:

    >>> factor_system([x, 1])
    []

    A system where any value of the symbol(s) is a solution:

    >>> factor_system([x - x, (x + 1)**2 - (x**2 + 2*x + 1)])
    [[]]

    A system with no generic solution:

    >>> factor_system([a*x*(x-1), b*y, c], [x, y])
    []

    If c is added to the unknowns then the system has a generic solution:

    >>> factor_system([a*x*(x-1), b*y, c], [x, y, c])
    [[x - 1, y, c], [x, y, c]]

    Alternatively :func:`factor_system_cond` can be used to get degenerate
    cases as well:

    >>> factor_system_cond([a*x*(x-1), b*y, c], [x, y])
    [[x - 1, y, c], [x, y, c], [x - 1, b, c], [x, b, c], [y, a, c], [a, b, c]]

    Each of the above cases is only satisfiable in the degenerate case `c = 0`.

    The solution set of the original system represented
    by eqs is the union of the solution sets of the
    factorized systems.

    An empty list [] means no generic solution exists.
    A list containing an empty list [[]] means any value of
    the symbol(s) is a solution.

    See Also
    ========

    factor_system_cond : Returns both generic and degenerate solutions
    factor_system_bool : Returns a Boolean combination representing all solutions
    sympy.polys.polytools.factor : Factors a polynomial into irreducible factors
                                   over the rational numbers
    c                 S  s   g | ]}t |s|qS r&   )_is_degenerater,   sysr&   r&   r'   rB   2      z!factor_system.<locals>.<listcomp>c                 S     g | ]	}d d |D qS )c                 S     g | ]}|  qS r&   r^   r,   rT   r&   r&   r'   rB   3  r~   z,factor_system.<locals>.<listcomp>.<listcomp>r&   r,   rl   r&   r&   r'   rB   3      _factor_system_poly_from_expr)r   r1   r   systemssystems_genericsystems_exprr&   r&   r'   factor_system  s   Tr   rl   
list[Poly]boolc                 C  s   t dd | D S )z2Helper function to check if a system is degeneratec                 s  s    | ]}|j V  qd S r   )rJ   r   r&   r&   r'   r.   9  s    z!_is_degenerate.<locals>.<genexpr>rZ   )rl   r&   r&   r'   r   7     r   r   c                 K  s$   t | |fi |}tdd |D  S )aV  
    Factorizes a system of polynomial equations into irreducible DNF.

    The system of expressions(eqs) is taken and a Boolean combination
    of equations is returned that represents the same solution set.
    The result is in disjunctive normal form (OR of ANDs).

    Parameters
    ==========

    eqs : list
       List of expressions to be factored.
       Each expression is assumed to be equal to zero.

    gens : list, optional
       Generator(s) of the polynomial ring.
       If not provided, all free symbols will be used.

    **kwargs : dict, optional
       Optional keyword arguments


    Returns
    =======

    Boolean:
       A Boolean combination of equations. The result is typically in
       the form of a conjunction (AND) of a disjunctive normal form
       with additional conditions.

    Examples
    ========

    >>> from sympy.solvers.polysys import factor_system_bool
    >>> from sympy.abc import x, y, a, b, c
    >>> factor_system_bool([x**2 - 1])
    Eq(x - 1, 0) | Eq(x + 1, 0)

    >>> factor_system_bool([x**2 - 1, y - 1])
    (Eq(x - 1, 0) & Eq(y - 1, 0)) | (Eq(x + 1, 0) & Eq(y - 1, 0))

    >>> eqs = [a * (x - 1), b]
    >>> factor_system_bool([a*(x - 1), b])
    (Eq(a, 0) & Eq(b, 0)) | (Eq(b, 0) & Eq(x - 1, 0))

    >>> factor_system_bool([a*x**2 - a, b*(x + 1), c], [x])
    (Eq(c, 0) & Eq(x + 1, 0)) | (Eq(a, 0) & Eq(b, 0) & Eq(c, 0)) | (Eq(b, 0) & Eq(c, 0) & Eq(x - 1, 0))

    >>> factor_system_bool([x**2 + 2*x + 1 - (x + 1)**2])
    True

    The result is logically equivalent to the system of equations
    i.e. eqs. The function returns ``True`` when all values of
    the symbol(s) is a solution and ``False`` when the system
    cannot be solved.

    See Also
    ========

    factor_system : Returns factors and solvability condition separately
    factor_system_cond : Returns both factors and conditions

    c                 S  s   g | ]}t d d |D  qS )c                 S  s   g | ]}t |d qS )r   r   )r,   rt   r&   r&   r'   rB   ~  rC   z1factor_system_bool.<locals>.<listcomp>.<listcomp>)r   r   r&   r&   r'   rB   ~  s    z&factor_system_bool.<locals>.<listcomp>)factor_system_condr   )r   r1   r   r   r&   r&   r'   factor_system_bool<  s   Ar   c                 K  s$   t | |fi |}dd |D }|S )a  
    Factorizes a polynomial system into irreducible components and returns
    both generic and degenerate solutions.

    Parameters
    ==========

    eqs : list
        List of expressions to be factored.
        Each expression is assumed to be equal to zero.

    gens : list, optional
        Generator(s) of the polynomial ring.
        If not provided, all free symbols will be used.

    **kwargs : dict, optional
        Optional keyword arguments.

    Returns
    =======

    list[list[Expr]]
        A list of lists of expressions, where each sublist represents
        an irreducible subsystem. Includes both generic solutions and
        degenerate cases requiring equality conditions on parameters.

    Examples
    ========

    >>> from sympy.solvers.polysys import factor_system_cond
    >>> from sympy.abc import x, y, a, b, c

    >>> factor_system_cond([x**2 - 4, a*y, b], [x, y])
    [[x + 2, y, b], [x - 2, y, b], [x + 2, a, b], [x - 2, a, b]]

    >>> factor_system_cond([a*x*(x-1), b*y, c], [x, y])
    [[x - 1, y, c], [x, y, c], [x - 1, b, c], [x, b, c], [y, a, c], [a, b, c]]

    An empty list [] means no solution exists.
    A list containing an empty list [[]] means any value of
    the symbol(s) is a solution.

    See Also
    ========

    factor_system : Returns only generic solutions
    factor_system_bool : Returns a Boolean combination representing all solutions
    sympy.polys.polytools.factor : Factors a polynomial into irreducible factors
                                   over the rational numbers
    c                 S  r   )c                 S  r   r&   r   r   r&   r&   r'   rB     r~   z1factor_system_cond.<locals>.<listcomp>.<listcomp>r&   r   r&   r&   r'   rB     r   z&factor_system_cond.<locals>.<listcomp>r   )r   r1   r   systems_polyr   r&   r&   r'   r     s   3r   list[list[Poly]]c              	   K  s   zt | g|R i |\}}d}W n$ ttfy5   td}t | |gfi |\}}|d js1J d}Y nw |rFtdd |D rDg gS g S t|S )z
    Convert expressions to polynomials and factor the system.

    Takes a sequence of expressions, converts them to
    polynomials, and factors the resulting system. Handles both regular
    polynomial systems and purely numerical cases.
    Fur   Tc                 s  s    | ]}|d kV  qdS )r   Nr&   r   r&   r&   r'   r.     r/   z0_factor_system_poly_from_expr.<locals>.<genexpr>)r   r   r   r   is_Numericalr2   factor_system_poly)r   r1   r   r8   optsonly_numbers_ur&   r&   r'   r     s   
r   r8   c                   s  t dd | D std| sg gS | d j | d jt  fdd| dd D s0tdg }| D ]F}| \}}|jd	u rBq4|jd
u rX|sMg   S |dd |D  q4tt	|
 d }t| d}dd |D }|| || q4|sg gS t|}t|S )a  
    Factors a system of polynomial equations into irreducible subsystems

    Core implementation that works directly with Poly instances.

    Parameters
    ==========

    polys : list[Poly]
        A list of Poly instances to be factored.

    Returns
    =======

    list[list[Poly]]
        A list of lists of polynomials, where each sublist represents
        an irreducible component of the solution. Includes both
        generic and degenerate cases.

    Examples
    ========

    >>> from sympy import symbols, Poly, ZZ
    >>> from sympy.solvers.polysys import factor_system_poly
    >>> a, b, c, x = symbols('a b c x')
    >>> p1 = Poly((a - 1)*(x - 2), x, domain=ZZ[a,b,c])
    >>> p2 = Poly((b - 3)*(x - 2), x, domain=ZZ[a,b,c])
    >>> p3 = Poly(c, x, domain=ZZ[a,b,c])

    The equation to be solved for x is ``x - 2 = 0`` provided either
    of the two conditions on the parameters ``a`` and ``b`` is nonzero
    and the constant parameter ``c`` should be zero.

    >>> sys1, sys2 = factor_system_poly([p1, p2, p3])
    >>> sys1
    [Poly(x - 2, x, domain='ZZ[a,b,c]'),
     Poly(c, x, domain='ZZ[a,b,c]')]
    >>> sys2
    [Poly(a - 1, x, domain='ZZ[a,b,c]'),
     Poly(b - 3, x, domain='ZZ[a,b,c]'),
     Poly(c, x, domain='ZZ[a,b,c]')]

     An empty list [] when returned means no solution exists.
     Whereas a list containing an empty list [[]] means any value is a solution.

    See Also
    ========

    factor_system : Returns only generic solutions
    factor_system_bool : Returns a Boolean combination representing the solutions
    factor_system_cond : Returns both generic and degenerate solutions
    sympy.polys.polytools.factor : Factors a polynomial into irreducible factors
                                   over the rational numbers
    c                 s  s    | ]}t |tV  qd S r   )
isinstancer   r,   polyr&   r&   r'   r.   	  s    z%factor_system_poly.<locals>.<genexpr>z(polys should be a list of Poly instancesr   c                 3  s$    | ]}|j  ko|jkV  qd S r   )r   r1   r   base_domain	base_gensr&   r'   r.     s   " r=   Nz8All polynomials must have the same domain and generatorsTFc                 S  r{   r&   r&   r,   r;   r}   r&   r&   r'   rB     r~   z&factor_system_poly.<locals>.<listcomp>)r   c                 S  r{   r&   r&   r   r&   r&   r'   rB      r~   )r2   	TypeErrorr   r1   r   factor_listis_zerork   r   r	   as_coeff_Mulr   _factor_sets_sort_systems)r8   factor_setsr   constantfactors_multconstpfactorsry   r&   r   r'   r     s4   7

 


r   
list[list]set[frozenset]c                   s0   | st  hS dd t|  D   fdd D S )z
    Helper to find the minimal set of factorised subsystems that is
    equivalent to the original system.

    The result is in DNF.
    c                 S  s   h | ]}t |qS r&   )	frozensetr   r&   r&   r'   r   4  r~   z$_factor_sets_slow.<locals>.<setcomp>c                   &   h | ] t  fd dD s qS )c                 3      | ]} |kV  qd S r   r&   r,   s2s1r&   r'   r.   5  r/   z._factor_sets_slow.<locals>.<setcomp>.<genexpr>r   r,   systems_setr   r'   r   5     & )r   r   )r   r&   r   r'   _factor_sets_slow+  s   r   c                   s   | st  hS t| td  fdd| D fdd D }t |r`| \}}}|s4t | q!t|tdfdd|D }D ]fdd|D }|hB }|||f qE|s#fddD S )	z1
    Helper that builds factor combinations.
    rH   c                      g | ]}| ur|qS r&   r&   r,   r   )current_setr&   r'   rB   @  r   z _factor_sets.<locals>.<listcomp>c                   s&   g | ]   fd dD  hfqS )c                      g | ]} |vr|qS r&   r&   r   factorr&   r'   rB   B  r   z+_factor_sets.<locals>.<listcomp>.<listcomp>r&   r   )
other_setsr   r'   rB   B  s    c                   r   r&   r&   r   )next_setr&   r'   rB   O  r   c                   r   r&   r&   r   )next_factorr&   r'   rB   R  r   c                   r   )c                 3  r   r   r&   r   r   r&   r'   r.   V  r/   z)_factor_sets.<locals>.<setcomp>.<genexpr>r   r   )ry   r   r'   r   V  r   z_factor_sets.<locals>.<setcomp>)r   r   r0   r   ri   r   rk   )r   stackr   remaining_setscurrent_solutionnext_remainingvalid_remainingnew_solutionr&   )r   r   r   r   ry   r'   r   8  s*   

r   r   Iterable[Iterable[Poly]]c                 C  s   dd | D }t |tddS )z$Sorts a list of lists of polynomialsc                 S  s   g | ]	}t |td dqS )TrI   reverse)rQ   _poly_sort_keyr   r&   r&   r'   rB   [  r   z!_sort_systems.<locals>.<listcomp>Tr   )rQ   _sys_sort_key)r   systems_listr&   r&   r'   r   Y  s   r   c                 C  s$   | j jr	| t} |  | j fS )zSort key for polynomials)r   is_FFr   r   r3   repto_list)r   r&   r&   r'   r   _  s   
r   c                 C  s   t ttt|  S )z!Sort key for lists of polynomials)rN   r   mapr   )r   r&   r&   r'   r   f  r   r   rx   )r&   )r   r   r1   r   r   r   r   r   )rl   r   r   r   )r   r   r1   r   r   r   r   r   )r   r   r1   r   r   r   r   r   )r8   r   r   r   )r   r   r   r   )r   r   r   r   )Cr%   
__future__r   typingr   collections.abcr   r   rO   sympyr   
sympy.corer   sympy.core.exprr   sympy.core.exprtoolsr	   sympy.core.sortingr
   sympy.logic.boolalgr   sympy.polysr   r   r   sympy.polys.domainsr   sympy.polys.polyoptionsr   sympy.polys.polytoolsr   r   sympy.polys.polyerrorsr   r   r   r   r   sympy.simplifyr   sympy.utilitiesr   sympy.utilities.iterablesr   sympy.utilities.miscr   r   r   sympy.core.relationalr    	Exceptionr!   r*   r4   r5   r   r   r   r   r   r   r   r   r   r   r   r   r&   r&   r&   r'   <module>   sN    >
C Bt
ZE
8

Y

!