
    MZd                       d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	m
Z
mZmZmZmZmZ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mZmZmZmZmZ d dl 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/m0Z1 d dl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 d dl9m:Z: d dl;m<Z<m=Z=m>Z> d dl?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZFmGZGmHZH d dlImJZJ d dlKmLZLmMZMmNZNmOZOmPZPmQZQ d dlRmSZS d dlTmUZU d dlVmWZWmXZXmYZYmZZZm[Z[ d dl\m]Z]m^Z^m_Z_ d dl`maZambZb d dlcmdZd d dlemfZfmgZg d dlhmiZi d dljmkZk d d llmmZmmnZnmoZo d d!lpmqZq d d"lrmsZsmtZt d d#lumvZv d d$lwmxZxmyZymzZzm{Z{ d d%l|m}Z} d d&l~Z~g d'd'fd(Zd) Zd* Zd+ Zd, Zd- ZdHd.Zd/ed'd'd0fd1Zd2 Zd3 ZdId4ZdJd5Zd6 ZdJd7Zd8 ZdKd9Zd: Zd; Zd< ZdLd=Z	 	 dMd>ZdNd?Zej*                  fd@ZdOdAZdKdBZ  evdCdDdEF      e/      Z.  evdGdDdEF      e1      Z0y&)P    )defaultdict)Product)Sum)BasicSAddMulPowSymbolsympifyexpand_funcFunctionDummyExprfactor_termsexpand_power_expEq)	factor_nc)global_parameters)
expand_log	count_ops_mexpandnfloat
expand_mulexpand)FloatIpiRational)
Relational)	Transform)ordered)_sympify)	bottom_upwalk)gammaexpsqrtlog	exp_polarre)CombinatorialFunction)
unpolarifyAbssign)ExpBase)HyperbolicFunction)ceiling)	Piecewisepiecewise_foldpiecewise_simplify)TrigonometricFunction)
BesselBasebesseljbesselibesselkbesselyjn)KroneckerDelta)Integral)
MatrixExprMatAddMatMulMatPowMatrixSymbol)togethercancelfactor)_is_sum_surds_minimal_polynomial_sq)combsimp)sub_presub_post)hyperexpand)powsimp)radsimpfractioncollect_abs)
sqrtdenest)trigsimpexptrigsimp)
deprecated)has_varietysiftsubsetsiterable)as_intNFc                 `    t        |       } |rt        t        | |      |      S t        | |      S )a  
    Separates variables in an expression, if possible.  By
    default, it separates with respect to all symbols in an
    expression and collects constant coefficients that are
    independent of symbols.

    Explanation
    ===========

    If ``dict=True`` then the separated terms will be returned
    in a dictionary keyed to their corresponding symbols.
    By default, all symbols in the expression will appear as
    keys; if symbols are provided, then all those symbols will
    be used as keys, and any terms in the expression containing
    other symbols or non-symbols will be returned keyed to the
    string 'coeff'. (Passing None for symbols will return the
    expression in a dictionary keyed to 'coeff'.)

    If ``force=True``, then bases of powers will be separated regardless
    of assumptions on the symbols involved.

    Notes
    =====

    The order of the factors is determined by Mul, so that the
    separated expressions may not necessarily be grouped together.

    Although factoring is necessary to separate variables in some
    expressions, it is not necessary in all cases, so one should not
    count on the returned factors being factored.

    Examples
    ========

    >>> from sympy.abc import x, y, z, alpha
    >>> from sympy import separatevars, sin
    >>> separatevars((x*y)**y)
    (x*y)**y
    >>> separatevars((x*y)**y, force=True)
    x**y*y**y

    >>> e = 2*x**2*z*sin(y)+2*z*x**2
    >>> separatevars(e)
    2*x**2*z*(sin(y) + 1)
    >>> separatevars(e, symbols=(x, y), dict=True)
    {'coeff': 2*z, x: x**2, y: sin(y) + 1}
    >>> separatevars(e, [x, y, alpha], dict=True)
    {'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1}

    If the expression is not really separable, or is only partially
    separable, separatevars will do the best it can to separate it
    by using factoring.

    >>> separatevars(x + x*y - 3*x**2)
    -x*(3*x - y - 1)

    If the expression is not separable then expr is returned unchanged
    or (if dict=True) then None is returned.

    >>> eq = 2*x + y*sin(x)
    >>> separatevars(eq) == eq
    True
    >>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None
    True

    )r   _separatevars_dict_separatevars)exprsymbolsdictforces       9/usr/lib/python3/dist-packages/sympy/simplify/simplify.pyseparatevarsrb   1   s2    F 4=D!-e"<gFFT5))    c                 z   t        | t              rc| j                  d   }|j                  rH|j                  s<t        |d|      }|*t        t        | j                  |j                                S | S t        | j                        dk  r| S | j                  rXt        | j                        }d}t        |      D ]   \  }}t        ||      ||<   |xs ||   |k7  }" |r | j                  | } | S | j                  rH| j                  t         j"                  k7  r+t%        t        | j                  |      | j&                        } | j)                  dd|      } |rt+        |       n| i f\  }}	t-        |      j/                  |	      } | j0                  s| S t        | j                        }|d   j3                  dd      d   }
|d	d  D ]  }|
|j3                  dd      d   z  }
 t        |
 }
|
j5                         d	   }
|
j3                  dd      d   }t        |      D ]4  \  }}|j3                  dd      \  }}||z
  }t        | t        | z  ||<   6 t7        | }t        |j                        d	kD  r>|}|rt+        |      n|i f\  }}	t-        |      j/                  |	      }|j0                  s|}|
|z  S )
Nr   T)r_   r`      Fr`   )mulmultinomialr`   )csetwarn   )
isinstancer.   argsis_Mul	is_numberrb   r	   mapfuncvalueslenfree_symbolslist	enumerateis_Powbaser   Exp1r
   r'   r   posifyrF   subsis_Addargs_cncas_coeff_Mulr   )r]   r`   argsrm   changedia_exprrepscommonccommonc_setcncnonsepars                  ra   r\   r\   {   s   $iil::cmmSt59A}C		188:677
4! {{DIIdO 	.DAq"1e,DG-aAG	. 499d#D {{tyyAFF*<		7B ;;5e5;AD"'&,dBZKE4%=d#D;; 		?D1gDu5a8G!"X 81::4e:4Q7787mG""$Q'G""5"9!<K $ #1

5
12Oq'#r("Q# DzH
8  !A%',fUm5"+t$$T*||H8rc   c                 :   |r)t        d |D              st        d      t        |      }n|d| iS t        | j                        }|sy |dgz   D ci c]  }|g  }}t	        j
                  |       D ]}  }|j                  }t        |      j                  |      }t        |      dkD  r y t        |      dk(  r|d   j                  |       \||j                            j                  |        |j                         D ]  \  }}t	        | ||<    |S c c}w )Nc              3   4   K   | ]  }|j                     y wN)is_Atom).0ts     ra   	<genexpr>z%_separatevars_dict.<locals>.<genexpr>   s     .199.s   zsymbols must be Atoms.coeffrk   r   )all
ValueErrorru   rt   r	   	make_argssetintersectionrs   appendpopitems)r]   r^   r   retexpsymr   kvs           ra   r[   r[      s   .g..566w-	t(()!WI-
.Q1b5
.C
.]]4  	.7|008|q |!L"  "#**1-	. 		 1aA J# /s   
Dc           	      "   t        |       } t        |       rt        |       }t        |       } t	               }| D ]&  }|j                  |j                  t                    }( i }|D ]A  }|j                  t        |      d   j                         D ci c]  \  }}||
 c}}       C t        |       D ]  \  }}|j                  |      | |<     ||       |j                         D 	ci c]  \  }}	|	|
 c}	}fS | j                  D ci c]1  }|j                  #|t        |j                   fddi|j"                  3 }}| j                  |      } | |j                         D 	ci c]  \  }}	|	|
 c}	}fS c c}}w c c}	}w c c}w c c}	}w )a^  Return ``eq`` (with generic symbols made positive) and a
    dictionary containing the mapping between the old and new
    symbols.

    Explanation
    ===========

    Any symbol that has positive=None will be replaced with a positive dummy
    symbol having the same name. This replacement will allow more symbolic
    processing of expressions, especially those involving powers and
    logarithms.

    A dictionary that can be sent to subs to restore ``eq`` to its original
    symbols is also returned.

    >>> from sympy import posify, Symbol, log, solve
    >>> from sympy.abc import x
    >>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True))
    (_x + n + p, {_x: x})

    >>> eq = 1/x
    >>> log(eq).expand()
    log(1/x)
    >>> log(posify(eq)[0]).expand()
    -log(_x)
    >>> p, rep = posify(eq)
    >>> log(p).expand().subs(rep)
    -log(x)

    It is possible to apply the same transformations to an iterable
    of expressions:

    >>> eq = x**2 - 4
    >>> solve(eq, x)
    [-2, 2]
    >>> eq_x, reps = posify([eq, x]); eq_x
    [_x**2 - 4, _x]
    >>> solve(*eq_x)
    [2]
    rk   positiveT)r   rX   typeru   r   unionatomsr   updaterz   r   rv   r{   rt   is_positiver   nameassumptions0)
eqfsymser   r   r   r   r   rs
             ra   rz   rz      s{   R 
B|H"Xu 	/A::aggfo.D	/ 	AAKK&)A,*<*<*>?$!QA?@	AbM 	!DAqFF4LBqE	!u

51q!t555 //DQ]]-B uQVV=d=ann== DD D	B.A1... @ 6D /s   E:+F 6F(Fc                 b   t        |       } | j                  ||dz         | z  }|j                  t              }|j	                  t
              rt        |      }|j                  d   d   }t        |      }t        |dd      }|j                  |      rt        |t        j                        S y)	a9  Given combinatorial term f(k) simplify its consecutive term ratio
       i.e. f(k+1)/f(k).  The input term can be composed of functions and
       integer sequences which have equivalent representation in terms
       of gamma special function.

       Explanation
       ===========

       The algorithm performs three basic steps:

       1. Rewrite all functions in terms of gamma, if possible.

       2. Rewrite all occurrences of gamma in terms of products
          of gamma and rising factorial with integer,  absolute
          constant exponent.

       3. Perform simplification of nested fractions, powers
          and if the resulting expression is a quotient of
          polynomials, reduce their total degree.

       If f(k) is hypergeometric then as result we arrive with a
       quotient of polynomials of minimal degree. Otherwise None
       is returned.

       For more information on the implemented algorithm refer to:

       1. W. Koepf, Algorithms for m-fold Hypergeometric Summation,
          Journal of Symbolic Computation (1995) 20, 399-417
    rk   r   Tr'   )deepcombine)ratioN)r   r{   rewriter&   hasr3   r4   rm   r   rM   is_rational_functionsimplifyr   Infinity)r   r   gs      ra   	hypersimpr     s    < 	
A	q!a%1A			%AuuY1FF2JqMAAe,Aa ,,rc   c                     t        t        t        | |f            \  } }| |z  j                  t              }|j                  dd      }|j                  |      S )a;  
    Returns True if ``f`` and ``g`` are hyper-similar.

    Explanation
    ===========

    Similarity in hypergeometric sense means that a quotient of
    f(k) and g(k) is a rational function in ``k``. This procedure
    is useful in solving recurrence relations.

    For more information see hypersimp().

    TF)rq   basic)ru   rp   r   r   r&   r   r   )r   r   r   hs       ra   hypersimilarr   G  sR     GaV$%DAq	
1eA	d%(A!!!$$rc   c                 P   |t         j                  }t        |       } t        | t        t
        f      r| j                  r| S | j                  d d       }t        t        |            }t        |t        t
        f      r|j                  r|S |j                  rq |j                  |j                  D cg c]  }t        |       c} }|s=t        |t              r-|j                         rt!        t"        j$                  | d      S |S |r|j                  d d       }|S c c}w )a  Make all Add sub-expressions canonical wrt sign.

    Explanation
    ===========

    If an Add subexpression, ``a``, can have a sign extracted,
    as determined by could_extract_minus_sign, it is replaced
    with Mul(-1, a, evaluate=False). This allows signs to be
    extracted from powers and products.

    Examples
    ========

    >>> from sympy import signsimp, exp, symbols
    >>> from sympy.abc import x, y
    >>> i = symbols('i', odd=True)
    >>> n = -1 + 1/x
    >>> n/x/(-n)**2 - 1/n/x
    (-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x))
    >>> signsimp(_)
    0
    >>> x*n + x*-n
    x*(-1 + 1/x) + x*(1 - 1/x)
    >>> signsimp(_)
    0

    Since powers automatically handle leading signs

    >>> (-2)**i
    -2**i

    signsimp can be used to put the base of a power with an integer
    exponent into canonical form:

    >>> n**i
    (-1 + 1/x)**i

    By default, signsimp does not leave behind any hollow simplification:
    if making an Add canonical wrt sign didn't change the expression, the
    original Add is restored. If this is not desired then the keyword
    ``evaluate`` can be set to False:

    >>> e = exp(y - x)
    >>> signsimp(e) == e
    True
    >>> signsimp(e, evaluate=False)
    exp(-(x - y))

    c                 ,    | j                   xr |   | k7  S r   rn   xs    ra   <lambda>zsignsimp.<locals>.<lambda>  s    qxx6qbEQJ rc   c                 
    |   S r    r   s    ra   r   zsignsimp.<locals>.<lambda>  s
    QB% rc   Fevaluatec                 ,    | j                   xr |   | k7  S r   r   r   s    ra   r   zsignsimp.<locals>.<lambda>  s     7rUaZ rc   c                 
    |   S r   r   r   s    ra   r   zsignsimp.<locals>.<lambda>  s
    aR5 rc   )r   r   r   rl   r   r    r   replacerK   rJ   r|   rq   rm   signsimpr   could_extract_minus_signr	   r   NegativeOne)r]   r   r   r   rvs        ra   r   r   ]  s    d $--4=DdT:./4<<6HAAa$
+,		xxQVV1662ahqk23Jr3 113q}}rcE::	II7IH 3s   4D#g333333?Tc           	      d   fdfd}t        | |      } j                  d|      j                  d      j                  d|      j                  d|      j                  d      d	t        | t              r*| j                  r| j
                  st        j                  S | S t        | d
d      }| |di S t        t        |             x}	} t        | t              r| j                  s| S |r.| j                  t              rt        |       } | j                  s| S t         t"        t$        t&        f| j)                  fdfdd      } t        |       s ||       S | j*                  st-        |       } d}
|dur$| j                  t.              rd}
t1        | d      } t3        | d       } t#        t5        |       j7                          } t9        |       } |t;        |      j9                               } t=        | d      t=        |d            }|t        j>                  u r|} n
 |||       } t        | t              s| S tA        | d      } | j                  tB              r| jE                  tF              } | j                  tH              rtK        |       }  ||       } | j                  tH              rwtK        |       } | j                  tL              rtO        |       } | j                  tH              r7tQ        | dd      } | j                  tH              r | tA        |             } | S tS        |       } | j                  tL              rtO        |       } | j                  tT              rtW        |       } | j                  tX        tZ              rt]        | d      } | j                  t^              r ta        | d      tc        |             } | j                  td        tf              rti        |       } | j                  tj              rtm        | fi } | j                  tn              r<| jq                  | js                  tn              D ci c]  }|tA        |       c}      } | j                  tt              rtw        | fi } ddl<m=} | j                  |      rddl>m?}  ||       }  t5        | dd      t5        |       |       } |t9        |            } |tA        |      t        t        |                  }|j                  tX        tZ        t&        t              rt        |      }t        d d       }|jq                  |      } | j                         \  }}|j                  rEt        t        d|z  dd            \  }}|t        j                  ur||z  j                         |z  } | j                         r#t        |       \  }}|dk7  rt        | | z        }  |       | |	      z  kD  r|	} |
r|t        | d      }  ||       S c c}w ) a  Simplifies the given expression.

    Explanation
    ===========

    Simplification is not a well defined term and the exact strategies
    this function tries can change in the future versions of SymPy. If
    your algorithm relies on "simplification" (whatever it is), try to
    determine what you need exactly  -  is it powsimp()?, radsimp()?,
    together()?, logcombine()?, or something else? And use this particular
    function directly, because those are well defined and thus your algorithm
    will be robust.

    Nonetheless, especially for interactive use, or when you do not know
    anything about the structure of the expression, simplify() tries to apply
    intelligent heuristics to make the input expression "simpler".  For
    example:

    >>> from sympy import simplify, cos, sin
    >>> from sympy.abc import x, y
    >>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2)
    >>> a
    (x**2 + x)/(x*sin(y)**2 + x*cos(y)**2)
    >>> simplify(a)
    x + 1

    Note that we could have obtained the same result by using specific
    simplification functions:

    >>> from sympy import trigsimp, cancel
    >>> trigsimp(a)
    (x**2 + x)/x
    >>> cancel(_)
    x + 1

    In some cases, applying :func:`simplify` may actually result in some more
    complicated expression. The default ``ratio=1.7`` prevents more extreme
    cases: if (result length)/(input length) > ratio, then input is returned
    unmodified.  The ``measure`` parameter lets you specify the function used
    to determine how complex an expression is.  The function should take a
    single argument as an expression and return a number such that if
    expression ``a`` is more complex than expression ``b``, then
    ``measure(a) > measure(b)``.  The default measure function is
    :func:`~.count_ops`, which returns the total number of operations in the
    expression.

    For example, if ``ratio=1``, ``simplify`` output cannot be longer
    than input.

    ::

        >>> from sympy import sqrt, simplify, count_ops, oo
        >>> root = 1/(sqrt(2)+3)

    Since ``simplify(root)`` would result in a slightly longer expression,
    root is returned unchanged instead::

       >>> simplify(root, ratio=1) == root
       True

    If ``ratio=oo``, simplify will be applied anyway::

        >>> count_ops(simplify(root, ratio=oo)) > count_ops(root)
        True

    Note that the shortest expression is not necessary the simplest, so
    setting ``ratio`` to 1 may not be a good idea.
    Heuristically, the default value ``ratio=1.7`` seems like a reasonable
    choice.

    You can easily define your own measure function based on what you feel
    should represent the "size" or "complexity" of the input expression.  Note
    that some choices, such as ``lambda expr: len(str(expr))`` may appear to be
    good metrics, but have other problems (in this case, the measure function
    may slow down simplify too much for very large expressions).  If you do not
    know what a good metric would be, the default, ``count_ops``, is a good
    one.

    For example:

    >>> from sympy import symbols, log
    >>> a, b = symbols('a b', positive=True)
    >>> g = log(a) + log(b) + log(a)*log(1/b)
    >>> h = simplify(g)
    >>> h
    log(a*b**(1 - log(a)))
    >>> count_ops(g)
    8
    >>> count_ops(h)
    5

    So you can see that ``h`` is simpler than ``g`` using the count_ops metric.
    However, we may not like how ``simplify`` (in this case, using
    ``logcombine``) has created the ``b**(log(1/a) + 1)`` term.  A simple way
    to reduce this would be to give more weight to powers as operations in
    ``count_ops``.  We can do this by using the ``visual=True`` option:

    >>> print(count_ops(g, visual=True))
    2*ADD + DIV + 4*LOG + MUL
    >>> print(count_ops(h, visual=True))
    2*LOG + MUL + POW + SUB

    >>> from sympy import Symbol, S
    >>> def my_measure(expr):
    ...     POW = Symbol('POW')
    ...     # Discourage powers by giving POW a weight of 10
    ...     count = count_ops(expr, visual=True).subs(POW, 10)
    ...     # Every other operation gets a weight of 1 (the default)
    ...     count = count.replace(Symbol, type(S.One))
    ...     return count
    >>> my_measure(g)
    8
    >>> my_measure(h)
    14
    >>> 15./8 > 1.7 # 1.7 is the default ratio
    True
    >>> simplify(g, measure=my_measure)
    -log(a)*log(b) + log(a) + log(b)

    Note that because ``simplify()`` internally tries many different
    simplification strategies and then compares them using the measure
    function, we get a completely different result that is still different
    from the input expression by doing this.

    If ``rational=True``, Floats will be recast as Rationals before simplification.
    If ``rational=None``, Floats will be recast as Rationals but the result will
    be recast as Floats. If rational=False(default) then nothing will be done
    to the Floats.

    If ``inverse=True``, it will be assumed that a composition of inverse
    functions, such as sin and asin, can be cancelled in any order.
    For example, ``asin(sin(x))`` will yield ``x`` without checking whether
    x belongs to the set where this relation is true. The default is
    False.

    Note that ``simplify()`` automatically calls ``doit()`` on the final
    expression. You can avoid this behavior by passing ``doit=False`` as
    an argument.

    Also, it should be noted that simplifying a boolean expression is not
    well defined. If the expression prefers automatic evaluation (such as
    :obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or
    ``False`` if truth value can be determined. If the expression is not
    evaluated by default (such as :obj:`~.Predicate()`), simplification will
    not reduce it and you should use :func:`~.refine()` or :func:`~.ask()`
    function. This inconsistency will be resolved in future version.

    See Also
    ========

    sympy.assumptions.refine.refine : Simplification using assumptions.
    sympy.assumptions.ask.ask : Query for boolean expressions using assumptions.
    c                  >    t        |       s| d   S t        |       S )z
        Return the choice that has the fewest ops. In case of a tie,
        the expression listed first is selected.
        r   key)rU   min)choicesmeasures    ra   shorterzsimplify.<locals>.shorter?  s$    
 7#1:7((rc   c                 P    r| j                         n| } |t        |            S r   )doitrP   )r   r   r   r   s     ra   donezsimplify.<locals>.doneH  s#    QVVX1r;r?++rc   rationalr   r   r   inverser   )r   r   r   r   r   _eval_simplifyNc                 ^    t        | t              xr | j                  xr t        |        S r   )rl   r   rm   )r   handleds    ra   r   zsimplify.<locals>.<lambda>m  s/    *Q% !&& w: 6 rc   c           
      p     | j                   | j                  D cg c]  }t        |fi  c} S c c}w r   )rq   rm   r   )r   r   kwargss     ra   r   zsimplify.<locals>.<lambda>o  s.    &!&&!&&AQ8A00AB As   3FsimultaneousTc                 .      t         d fd             S )Nnormalc                       S r   r   ws   ra   r   z,simplify.<locals>.<lambda>.<locals>.<lambda>  s    1 rc   )getattrr   s   `ra   r   zsimplify.<locals>.<lambda>  s    &Ega9&E&G rc   r   )r/   )r   r   r   )Quantity)quantity_simplifyr'   )r   r   c                 &    t        | j                   S r   )r	   rm   r   s    ra   r   zsimplify.<locals>.<lambda>  s    #qvv, rc   c                     | j                   xr\ t        | j                        dk(  xrB | j                  d   j                  xr' | j                  d   j                  xr | j
                  S )Nre   r   rk   )rn   rs   rm   	is_Numberr|   is_commutativer   s    ra   r   zsimplify.<locals>.<lambda>  sa    	 	AFFq		q		 	
q		 	
 rc   rk   )symbolic	max_terms)exponentr   )Mr   getrl   r   is_zeror   r   Zeror   rP   r   r   rm   r   r   inversecombiner   r	   r
   r0   r   r   nc_simplifyr   	nsimplify
_bottom_uprM   as_content_primitiverE   r   rD   r   r   r/   r   r.   r3   r4   r=   kroneckersimpr5   rL   r7   
besselsimpr6   r1   rR   r)   r   
logcombiner,   r&   rI   r   sum_simplifyr>   xreplacer   r   product_simplifysympy.physics.unitsr   sympy.physics.units.utilr   r   r   r'   rS   r!   as_numer_denomr|   rO   rN   Oner   r   r   )r]   r   r   r   r   r   r   r   r   original_exprfloats_eexpr1expr2r   r   r   short
hollow_mulnumerdenomndr   r   s     `  ``                @@ra   r   r     s;   v), 4(+DGU+::i1JJz84::i1

64(*F $$,,!^^qvv55T#3T:N!'''&x~66MDdE"$))488H%d#yyK 3W$G<<	B  	D dG$Dz4  Fu%-dGHD2245D	BB++-.EHT-xD/IJE

ueT*dE"5)D xx~||C  xx	d#Dz88I "$'Dxx'$T*xx	" *$TF88I&"4d);<D  K tDxxT"xx
$xx%'9:4(xx}z$T2Jt4DExx%u- ~xx}D+F+xx}}(,

8(<>#$A|A> ? xx//,xx> &GD%d;WT]DQEE6%=)EE<.0@EAR0STEyy&(:GSIE" 	J >>*%D&&(LE5||%%1EF1AEE>!G##%a'D$$&~16QBG$Dt}uW]333 ("dU+:_>s   #X-c                 d   t        | t              sR| j                  | j                  t              D ci c]$  }|j	                  t
              r|t        |fi |& c}      } t        |       } t        | t              s| S | j                  }g }g }|D ]|  }t        t        j                  |      d d      \  }}|s|j                  |       <t        | g}|j                  t        ||D  cg c]  }  | j                  di | c} z           ~ t        t        |      g| }	|	S c c}w c c} w )z$Main function for Sum simplificationc                 "    t        | t              S r   rl   r   )r   s    ra   r   zsum_simplify.<locals>.<lambda>
  s    jC( rc   T)binaryr   )rl   r   r   r   r   r   r   r   rm   rV   r	   r   r   r   sum_combine)
r   r   r   termss_to_tterm	sum_termsotherresults
             ra   r   r     s!   aJJWWS\1QUU3Z <4V44 1 2q	AaFFE
C
C Td 3(7	5JJte

3i!P"2!"2"2"<V"<!PPRST S!(C(FM+1" "Qs   )D(,D-c                    dgt        |       z  }t        d      D ]m  }t        |       D ]]  \  }}||   rt        |       D ]D  \  }}||   r||k7  st        |||      }t	        |t
        t        f      s6|| |<   | |   }d||<   F _ o t        j                  }t        |       D ]  \  }}	||   rt        ||	      } |S )zHelper function for Sum simplification

       Attempts to simplify a list of sums, by combining limits / sum function's
       returns the simplified sum
    Fre   T)
rs   rangerv   sum_addrl   r   r	   r   r   r   )
r  usedmethodr   s_term1js_term2tempr  s_terms
             ra   r  r    s     7SXD( 	+#C. 	+JAw7"+C. +JAw7qAv&w@%dS#J7%)CF&)!fG&*DG+	+	+ VVFs^ )	6Aw(F) Mrc   c                 H    ||||d}|rt        | g| n| }t        |fi |S )a  Return Sum with constant factors extracted.

    If ``limits`` is specified then ``self`` is the summand; the other
    keywords are passed to ``factor_terms``.

    Examples
    ========

    >>> from sympy import Sum
    >>> from sympy.abc import x, y
    >>> from sympy.simplify.simplify import factor_sum
    >>> s = Sum(x*y, (x, 1, 3))
    >>> factor_sum(s)
    y*Sum(x, (x, 1, 3))
    >>> factor_sum(s.function, s.limits)
    y*Sum(x, (x, 1, 3))
    )radicalclearrO   r/   )r   r   )selflimitsr'  r(  rO   r/   r   r]   s           ra   
factor_sumr+  1  s8    & !5d,F!'3tfTD'''rc   c                    d }t        | t              r	 ||       }n| }t        |t              r	 ||      }n|}t        |      t        |      u ry|dk(  rP|j                  |j                  k(  rZt	        t        |j                  |j                  z   g|j                         S |dk(  rt        |j                  |j                  z
        dk(  rt        |j                        t        |j                        cxk(  rdk(  rn n|j                  d   d   }|j                  d   d   }|j                  d   d   }|j                  d   d   }	|j                  d   d   }
|j                  d   d   }||	k(  rT|
|dz   k(  r"t	        t        |j                  |||f            S ||dz   k(  r"t	        t        |j                  ||
|f            S t        | |      S )z&Helper function for Sum simplificationc                     t        j                  |       }t        d |D              }t        |D cg c]
  }||k7  s	| c} }t        ||j                  z  g|j
                   S c c}w )Nc              3   B   K   | ]  }t        |t              s|  y wr   r  )r   r   s     ra   r   z.sum_add.<locals>.__refactor.<locals>.<genexpr>Q  s     :!z!S'9A:s   )r	   r   nextr   functionr*  )valrm   sumvr   constants        ra   
__refactorzsum_add.<locals>.__refactorO  s]    }}S!:t::D6qAI678dmm+:dkk:: 7s
   
A'A'r   rk   re   )
rl   r	   r   r*  r+  r   r0  r   rs   r   )r)  r  r   r4  rselfrotherr   x1y1r"  x2y2s               ra   r  r  J  s   
; $4 %E"E{d6l"Q;||v}},!#ennv&F"V"VWWq[89Q>u||$FMM(:?a?Q*Aa+Ba+Ba(+Aq)!,Bq)!,BAva<#-c%..1b"+.N#OO26\#-c%..1b"+.N#OOtUrc   c           
         t        j                  |       }g }g }|j                  dd      }|D ]w  }t        |t              rT|r@|j                  t	         |j                  j                  di |g|j                          U|j                  |       g|j                  |       y dgt        |      z  }t        d      D ]b  }t        |      D ]R  \  }	}
||	   rt        |      D ]9  \  }}||   r|	|k7  st        |
||      }t        |t              s0|||	<   d||<   ; T d t        | }t        |      D ]  \  }	}||	   rt        ||      } |S )z(Main function for Product simplificationr   TFre   r   )r	   r   r   rl   r   r   r0  r   r*  rs   r  rv   product_mul)r   r   r  p_tr  r   r  r  r   r   p_term1r"  p_term2tmp_prodr  p_terms                   ra   r   r   v  sc   MM!E
C
C::fd#D dG$

7#94==#9#9#CF#C 1$(KK1 2 

4 JJt 7SXD( +#C. 	+JAw7"+C. +JAw7qAv#.w#H%h8%-CF&*DG+	++ #YFs^ )	6Aw(F) Mrc   c                    t        |       t        |      u r^|dk(  rG| j                  |j                  k(  r?t        | j                  |j                  z  g| j                   S |dk(  rt	        | j                  |j                  z
        dk(  rt        | j                        t        |j                        cxk(  rdk(  rn n| j                  d   d   }| j                  d   d   }| j                  d   d   }|j                  d   d   }|j                  d   d   }|j                  d   d   }||k(  rB||dz   k(  rt        | j                  |||f      S ||dz   k(  rt        | j                  |||f      S t        | |      S )z*Helper function for Product simplificationr   rk   re   )r   r*  r   r0  r   rs   r	   )	r)  r  r   r   r7  r8  r"  r9  r:  s	            ra   r<  r<    sN   DzT%[ Q;{{ell*t}}u~~=LLLq[671<t{{#s5<<'8=A=Aq)AQ*BQ*BQ*Aa+Ba+BAva<#*4==1b"+#FF26\#*4==1b"+#FFtUrc   c                 r   ddl m} |dz  dk(  r"t        t        |             } |dz  }|dz  dk(  r"|dk(  r| S | t	        d|      z  }t        d      }t        | ||      }|y |||      }|D ]H  }t        ||z
        j                         dd|z  z  k  s)t        |      }t        ||z        | k(  sF|c S  y)	zm
     helper function for ``nthroot``
     It denests ``p**Rational(1, n)`` using its minimal polynomial
    r   )solvere   rk   r   Ng      ?
   )
sympy.solversrD  rQ   r(   r   r   rH   absr  r   )	pr  precrD  pnr   r   solssols	            ra   _nthroot_solverM    s    
 $
a%1*tAwF a%1* 	Av	
HQN	BsAq!Q'AyA;D sRx=??r"d({*S/CQ1$
	rc   c                 &    fd}t        | |      S )a  
    Takes logarithms and combines them using the following rules:

    - log(x) + log(y) == log(x*y) if both are positive
    - a*log(x) == log(x**a) if x is positive and a is real

    If ``force`` is ``True`` then the assumptions above will be assumed to hold if
    there is no assumption already in place on a quantity. For example, if
    ``a`` is imaginary or the argument negative, force will not perform a
    combination but if ``a`` is a symbol with no assumptions the change will
    take place.

    Examples
    ========

    >>> from sympy import Symbol, symbols, log, logcombine, I
    >>> from sympy.abc import a, x, y, z
    >>> logcombine(a*log(x) + log(y) - log(z))
    a*log(x) + log(y) - log(z)
    >>> logcombine(a*log(x) + log(y) - log(z), force=True)
    log(x**a*y/z)
    >>> x,y,z = symbols('x,y,z', positive=True)
    >>> a = Symbol('a', real=True)
    >>> logcombine(a*log(x) + log(y) - log(z))
    log(x**a*y/z)

    The transformation is limited to factors and/or terms that
    contain logs, so the result depends on the initial state of
    expansion:

    >>> eq = (2 + 3*I)*log(x)
    >>> logcombine(eq, force=True) == eq
    True
    >>> logcombine(eq.expand(), force=True)
    log(x**2) + I*log(x**3)

    See Also
    ========

    posify: replace all symbols with symbols having positive assumptions
    sympy.core.function.expand_log: expand the logarithms of products
        and powers; the opposite of logcombine

    c                 h   | j                   s| j                  s| S fd}fd}g }g }t        t              t	        j
                  |       D ]Z  }t        |t              r ||      rd   j                  g |f       3|j                  s|j                  |       Qg }g }g }|j                  D ]  }	|	j                  r7|	dk  r2|j                  t        j                         |j                  |	        Ft        |	t              r ||	      r|j                  |	       p ||	      r|j                  |	       |j                  |	        t        |      dkD  r|j                  |||f       $|r$t        |         j                  ||d   f       J|j                  |       ] t        |      dk(  r7t        |d   t              r$d   j                  g |j                         f       |st!        fdD              r| S |D ]  \  }
}}t        t#        |            }t        |j                  d      j                  d   t%        | z        }|r/|j                  d      }t        |j                  d   |z        }|r/t%        |
 |}}t        |t              r|f   j                  g |f       |j                  ||z          t        j'                               D ]a  }t        t)        t%        j                  |      D cg c]  \  }}|j                  d   t%        | z   c}}       d	      t%        | <   c t#        t        j'                                     D ]  }|vr| v r|| }}|j+                         |j+                         kD  r||}}|j                  |t        j                  |      j                  d   j                  |      j                  d   z  d	      z         |j                  |j                  |      z          t	        | S c c}}w )
Nc                 l    | t         j                  uxr  | j                  xs xr | j                  duS )NF)r   r   is_extended_real)r   r`   s    ra   goodaz$logcombine.<locals>.f.<locals>.gooda  s;     Q]]* R##Pu'P1C1C51PSrc   c                 b    | j                   d   }|j                  xs xr |j                  duS )Nr   F)rm   r   is_nonpositive)lr   r`   s     ra   goodlogz&logcombine.<locals>.f.<locals>.goodlog  s/    q	A==KE$Ka.>.>e.KKrc   r   r   rk   c              3   Z   K   | ]"  }t        |         d k(  xr |   d   g k(   $ yw)rk   r   N)rs   )r   r   log1s     ra   r   z(logcombine.<locals>.f.<locals>.<genexpr>-  s3     QqCQLA-B$q'!*2BBQs   (+rf   Fr   )r|   rn   r   ru   r   r   rl   r)   r   rm   is_Rationalr   r   rs   tupler   r   r"   r	   keysr   r   )r   rR  rV  r  logsr   otcoloaior   rU  lir   r   numdenrX  r`   s                     @ra   r   zlogcombine.<locals>.f  s   		RYYI	S	L
 4 r" 	$A!S!gajRQ(XXQ&& 	&B~~"q&		!--0		2##B,		"r		"		"	& r7Q;KKR-rO**B1;7LLO1	$8 u:?z%(C8HOOR-. QDQQI  
	"GAq!WQZ AAEE!HMM!$c1g-.AUU1X
A&  7AqA!S!aT
!!2q'*QqS!
	" diik" 	.A
3/3xx{1<'+q!q	37"1< ,=!',.DaM	. diik*+ 	,A}rTz qbS==?S]]_4"CCDHHSM..q1$((3-2D2DQ2GG%*, ,- Qtxx{]+	, E{)1<s   "P.r   )r]   r`   r   s    ` ra   r   r     s    \]~ dArc   c                      d }t        | |      S )a  Simplify the composition of a function and its inverse.

    Explanation
    ===========

    No attention is paid to whether the inverse is a left inverse or a
    right inverse; thus, the result will in general not be equivalent
    to the original expression.

    Examples
    ========

    >>> from sympy.simplify.simplify import inversecombine
    >>> from sympy import asin, sin, log, exp
    >>> from sympy.abc import x
    >>> inversecombine(asin(sin(x)))
    x
    >>> inversecombine(2*log(exp(3*x)))
    6*x
    c                    t        | t              rzt        | j                  d   t              sC| j                  d   j                  r| j                  d   j
                  t        j                  k(  r| j                  d   j                  } n| j                  rt        | d      rt        | j                        dk(  rjt        | j                  d   j                        dk(  rEt        | j                  d   | j                  d            r| j                  d   j                  d   } | j                  rP| j
                  t        j                  k(  r3t        | j                  t              r| j                  j                  d   } | S )Nr   r   rk   )argindex)rl   r)   rm   r'   rw   rx   r   ry   is_Functionhasattrrs   r   )r   s    ra   r   zinversecombine.<locals>.fs  s    b#"''!*c*rwwqz/@/@RWWQZ__XYX^X^E^WWQZ^^^^I 6BGG!c"''!*//&:a&?"''!*bjj!j&<=WWQZ__Q'99AFF*"&&#&VV[[^	rc   re  )r]   r   s     ra   r   r   ]  s    , dArc   c                     d fd}| j                  t              s| S | j                  t              r| j                  t              } | }d} || k7  r|} | j	                  d |      }|| k7  r| S )aQ  
    Simplify expressions with KroneckerDelta.

    The only simplification currently attempted is to identify multiplicative cancellation:

    Examples
    ========

    >>> from sympy import KroneckerDelta, kroneckersimp
    >>> from sympy.abc import i
    >>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i))
    1
    c                     t        d      D ]n  }t        d      D ]^  }| |   }||   }| |dz   dz     }||dz   dz     }t        ||      t        j                  u s@t        ||      t        j                  u s]  y p y)Nre   rk   TF)r  r   r   truefalse)args1args2i1i2a1a2a3a4s           ra   args_cancelz"kroneckersimp.<locals>.args_cancel  s    ( 	 BAh  2Y2YBFa<(BFa<(b":'Br2J!'',A 	  rc   c                     | j                   }|D cg c]  }t        |t              s| }}t        |d      D ];  \  }}|j                   }|j                   } ||      s(t        j
                  | z  c S  | S c c}w )Nre   )rm   rl   r=   rW   r   r   )	mrm   r   deltasdelta1delta2ro  rp  rw  s	           ra   cancel_kronecker_mulz+kroneckersimp.<locals>.cancel_kronecker_mul  sy    vv!CZ>%B!CC%fa0 	"NFFKKEKKE5%(vvz!		"
  Ds
   A:A:Nc                 "    t        | t              S r   )rl   r	   )r   s    ra   r   zkroneckersimp.<locals>.<lambda>  s    As); rc   )r   r=   r3   r   r   )r]   r}  newexprrw  s      @ra   r   r     sr    	 88N#xx	||N+GD
T/,,;=QR T/ Krc   c           
        	 d }d }d }| }t         t        t         t        z  dz        t        t          t        z  dz        g}| j                  t         |t         |t        t
              |            } | j                  t
         |t
         |t
        t              |            } dt        t         t        z        g}| j                  t         |t         |t              |            } | j                  t
         |t
         |t
              |            } t        d      		fd}| j                  t         |t                    } | j                  t         |t                    } | j                  t
         |t
                    } | j                  t         |t                    } d } ||       } | |k7  r| j                         } | S )	aA  
    Simplify bessel-type functions.

    Explanation
    ===========

    This routine tries to simplify bessel-type functions. Currently it only
    works on the Bessel J and I functions, however. It works by looking at all
    such functions in turn, and eliminating factors of "I" and "-1" (actually
    their polar equivalents) in front of the argument. Then, functions of
    half-integer order are rewritten using strigonometric functions and
    functions of integer order (> 1) are rewritten using functions
    of low order.  Finally, if the expression was changed, compute
    factorization of the result with factor().

    >>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S
    >>> from sympy.abc import z, nu
    >>> besselsimp(besselj(nu, z*polar_lift(-1)))
    exp(I*pi*nu)*besselj(nu, z)
    >>> besselsimp(besseli(nu, z*polar_lift(-I)))
    exp(-I*pi*nu/2)*besselj(nu, z)
    >>> besselsimp(besseli(S(-1)/2, z))
    sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z))
    >>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z))
    3*z*besseli(0, z)/2
    c                 0     t               fd}|S )Nc                 p    j                  t        j                  |            r	 | |      S  | |      S r   )r   r	   r   )nuzfactorsfrotos     ra   replz*besselsimp.<locals>.replacer.<locals>.repl  s2    ##CMM!$45"ay r1:rc   )r   )r  r  r  r  s   ``` ra   replacerzbesselsimp.<locals>.replacer  s    g,	 rc   c                       fd}|S )Nc                 4     | |      j                        S r   )r   )r  r  r  r  s     ra   tofuncz-besselsimp.<locals>.torewrite.<locals>.tofunc  s    r1:%%b))rc   r   )r  r  r  s   `` ra   	torewritezbesselsimp.<locals>.torewrite  s    	*rc   c                       fd}|S )Nc                 z    t        t        t        z  | z         | t        t         t        z        |z        z  S r   )r'   r   r   r*   )r  r  r  s     ra   r  z+besselsimp.<locals>.tominus.<locals>.tofunc  s1    qtBw<B	1"R%(8(: ;;;rc   r   )r  r  s   ` ra   tominuszbesselsimp.<locals>.tominus  s    	<rc   re   r   r  c                       fd}|S )Nc           
      j   | dz  t         j                  k(  rjt        t        t	         |       j                  t              j                  t              j                  d            j                  |                  S | j                  r| dkD  r | |      j                  d      S  | |      S )Nrk   T)rq   )r   Halfr   rR   r-   r   r8   r<   r   r{   
is_Integer)r  r  r  z0s     ra   r  z*besselsimp.<locals>.expander.<locals>.repl  s    Q166!B++G4<<R@GG!% H '*((,R!5 6 6 262qz((d(33r1:rc   r   )r  r  r  s   ` ra   expanderzbesselsimp.<locals>.expander  s    	 rc   c                     d }| j                  t              r |t        |       } | j                  t              r |t        |       } | S )Nc                 f    	 |j                   fd      }	 t        |d       D ]o  }|j                  \  }}  |dz   |      }  |dz   |      }|j                  |      s<|j                  |      sN|j	                  |d|dz   z  |z  |z  |z
        } n |S 	 # t
        t        f$ r |cY S w xY w)Nc                     t        |       S r   )rl   )r   bessels    ra   r   zTbesselsimp.<locals>._bessel_simp_recursion.<locals>._use_recursion.<locals>.<lambda>  s    jF.C rc   c                 2    t        | j                  d         S )Nr   )r+   rm   r   s    ra   r   zTbesselsimp.<locals>._bessel_simp_recursion.<locals>._use_recursion.<locals>.<lambda>  s    BqvvayM rc   r   rk   re   )findsortedrm   r   r{   r   	TypeError)r  r]   besselsbar   r   bap1bap2s   `       ra   _use_recursionzBbesselsimp.<locals>._bessel_simp_recursion.<locals>._use_recursion  s    ))$CD $W2IJ $!ww1%ac1~%ac1~88D>dhhtn#'99RAaC4$1F#GD!$  $ "  #I.  K s   A	B "B 4%B B0/B0)r   r8   r;   )r]   r  s     ra   _bessel_simp_recursionz*besselsimp.<locals>._bessel_simp_recursion  s>    	  88G!'40D88G!'40Drc   )
r   r*   r   r   r8   r9   r   r;   r:   rF   )
r]   r  r  r  	orig_exprifactorsminusfactorsr  r  r  s
            @ra   r   r     sw   @

 I9QrT!V$i2a&89H<<''7#X/0D <<''7#X/0D 	!B$(L<<'77#3\BDD<<'77#3\BDD 
sB	 <<'!23D<<'!23D<<'!23D<<'!23D. "$'Dy{{}Krc   c                 ^   t        |       } t        |      }| t        d|      z  }|j                  s|S t        |       s|S g }| j                  D cg c]  }|j                          }}|D ]|  \  }}|j                  s|c S |t        j                  u r)|j                  r3|j                  t        j                  k(  r|j                  j                  s|c S |j                  |       ~ |j                          |d| }| dk  rJ|dz  dk(  rB|  t        d|      z  }t        ||      }	t!        |	|z        t!        |        k(  r|	}
|
 S |}
|
 S t        ||      }	t!        |	      t!        |      ur%t!        |	|z        t!        |       k(  rt!        |	      S t#        | ||      } | |S | S c c}w )a"  
    Compute a real nth-root of a sum of surds.

    Parameters
    ==========

    expr : sum of surds
    n : integer
    max_len : maximum number of surds passed as constants to ``nsimplify``

    Algorithm
    =========

    First ``nsimplify`` is used to get a candidate root; if it is not a
    root the minimal polynomial is computed; the answer is one of its
    roots.

    Examples
    ========

    >>> from sympy.simplify.simplify import nthroot
    >>> from sympy import sqrt
    >>> nthroot(90 + 34*sqrt(7), 3)
    sqrt(7) + 3

    rk   Nr   re   )	constants)r   r   
is_integerrG   rm   r~   is_rationalr   r  rw   r'   r  rx   r   sortr   r   rM  )r]   r  max_lenrI  rH  surdsr   
coeff_mulsyr   ress              ra   nthrootr  )  s   6 4=D
Ahq!nA<<E,0II6q!.."6J6 1}}H:QUUaff_1B1BHQ 
JJL(7OEaxAEQJUXa^#a5)AqD>Xte_4at ;<t!u%A{(1+%(1a4.HTN*J{$4(D|K- 7s   F*c           
         	 t        t        |             S # t        t        f$ r Y nw xY wt        |       j	                  t        d      t        j                  t        d      t        j                  i      } | t        j                  u s| t        j                  u r| S |s| j                  rt        | |      S kdt        dg| j                  t
              D cg c]5  }t        j                  j                  j!                  |j"                        7 nc c}w c}z          z  dt%        dz        i |D ]R  }t        |      }|j'                        }|j(                  st        d      |j+                        t-        |      <   T | j'                  d	      }	|	j/                         \  }
}|
j0                  r|j0                  s| S fd
}	 |
r ||
      }
|r ||      }n"# t        $ r |t        | |      cY S | cY S w xY w|
|t        j2                  z  z   }|| k7  s|du r|S t        | |      S )a	  
    Find a simple representation for a number or, if there are free symbols or
    if ``rational=True``, then replace Floats with their Rational equivalents. If
    no change is made and rational is not False then Floats will at least be
    converted to Rationals.

    Explanation
    ===========

    For numerical expressions, a simple formula that numerically matches the
    given numerical expression is sought (and the input should be possible
    to evalf to a precision of at least 30 digits).

    Optionally, a list of (rationally independent) constants to
    include in the formula may be given.

    A lower tolerance may be set to find less exact matches. If no tolerance
    is given then the least precise value will set the tolerance (e.g. Floats
    default to 15 digits of precision, so would be tolerance=10**-15).

    With ``full=True``, a more extensive search is performed
    (this is useful to find simpler numbers when the tolerance
    is set low).

    When converting to rational, if rational_conversion='base10' (the default), then
    convert floats to rationals using their base-10 (string) representation.
    When rational_conversion='exact' it uses the exact, base-2 representation.

    Examples
    ========

    >>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi
    >>> nsimplify(4/(1+sqrt(5)), [GoldenRatio])
    -2 + 2*GoldenRatio
    >>> nsimplify((1/(exp(3*pi*I/5)+1)))
    1/2 - I*sqrt(sqrt(5)/10 + 1/4)
    >>> nsimplify(I**I, [pi])
    exp(-pi/2)
    >>> nsimplify(pi, tolerance=0.01)
    22/7

    >>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact')
    6004799503160655/18014398509481984
    >>> nsimplify(0.333333333333333, rational=True)
    1/3

    See Also
    ========

    sympy.core.function.nfloat

    infz-infrE        gp=
ף
@zconstants must be real-valuedT)chopc                    t         j                  j                  }| j                        }	 
sjshdt         j                  _        t        j                  |dg      }|:t        t        |d          t        |d               |t         j                  _        S 	t         j                  _        t        j                  |
      }|st        r|d   }t        |      }| r|st        |j                  du r(|t         j                  t         j                  fvrt        ||t         j                  _        S # |t         j                  _        w xY w)Nr  rk   r   )r  tolfullF)mpmathmpdps
_to_mpmathpslqr   intidentifyr   r   	is_finiter  ninf)r   origxvratr  r]   bprecconstants_dictr  rI  	tolerances         ra   nsimplify_realz!nsimplify.<locals>.nsimplify_real  s   yy}}\\% 	! "		kk2q'*?#SQ[L#c!f+>" !FIIM! !FIIMoobND*G  !!*7#D  ~~&2fjj&++5N+N   !FIIMDFIIMs   AD9 B	D9 9E)rational_conversionF)r   rY   r  r   r   r   r   r   NegativeInfinityrt   _real_to_rationalr   r   r  libmplibmpfprec_to_dps_precr  evalfis_Floatr  stras_real_imagr   ImaginaryUnit)r]   r  r  r  r   r  r  r3  r   exprvalr+   imr  r   r  r  rI  s     ``          @@@ra   r   r   e  s0   lvd|$$z" 4=!!eajjfq))#
 D qzzTQ%7%774$$ y2EFF
 bTjj') ll!!--agg6 ) )) * * *	
 DT	NEN <8$NN4 zz<==()U(;s8}%< jjDj)G!!#FB LLR\\! !6#B#B $T?RSS
 
b 	 B 
TzX&	T7JKKs*    --:DG2 2HHHc           
         t        |       } t        d      }| }i }d}||dk  rt        d|z        }|j                  t              D ]  }|}|t	        |      j                  |      }	n|G|dk\  rB|j                  du r4t	        |t        ||z        z        j                  t        |            }	n7|dk(  rt	        |      }	|	||<   |dk7  rt        d      t        |d      }	|r|	st	        |      }	n|	j                  s||| fv rt        j                  }	n|d	k  r]| }t        d
t        t        j                   |      t        j                   d
      z              }
t	        t#        ||
z               |
z  }	nn|d	kD  rYt        d
t        t        j                   |      t        j                   d
      z              }
t	        t#        ||
z              |
z  }	nt        j$                  }	|	||<    |j'                  |d      S )a)  
    Replace all reals in expr with rationals.

    Examples
    ========

    >>> from sympy.simplify.simplify import _real_to_rational
    >>> from sympy.abc import x

    >>> _real_to_rational(.76 + .1*x**.5)
    sqrt(x)/10 + 19/25

    If rational_conversion='base10', this uses the base-10 string. If
    rational_conversion='exact', the exact, base-2 representation is used.

    >>> _real_to_rational(0.333333333333333, rational_conversion='exact')
    6004799503160655/18014398509481984
    >>> _real_to_rational(0.333333333333333)
    1/3

    r  Nrk   Fexactbase10z/rational_conversion must be 'base10' or 'exact'r   r   rE  Tr   )r#   r   r2   r   r   limit_denominatorr  roundr  r   r   rY  r   ComplexInfinityr
   r  r)   r  r   r{   )r]   r  r  r  rH  r   
reduce_numflr   r   r  s              ra   r  r    s   , D>D
,CADJQQy[)
ggen  !..z:A#	Q&5I#66 ##C	N3  #g-RLS	$0 !RSS"u-A!RL]]#t$))A!VBBFJJrN6::b>$A BCA!#bd),,Q.A!VBFJJrN6::b>$A BCA RT+A-AAS	A B 66$T6**rc   c                 n   d}| j                   }| j                  rt        j                  || z
  fS | r^|| k7  rY| }|r| j	                         nt        |       j                  d      \  }} ||z  }| j                  d      \  }} ||z  }| r|| k7  rYt        | d      } | j                         r|  } | }| |fS )ah  Return `p, r` where `p` is the expression obtained when Rational
    additive and multiplicative coefficients of `expr` have been stripped
    away in a naive fashion (i.e. without simplification). The operations
    needed to remove the coefficients will be applied to `rhs` and returned
    as `r`.

    Examples
    ========

    >>> from sympy.simplify.simplify import clear_coefficients
    >>> from sympy.abc import x, y
    >>> from sympy import Dummy
    >>> expr = 4*y*(6*x + 3)
    >>> clear_coefficients(expr - 2)
    (y*(2*x + 1), 1/6)

    When solving 2 or more expressions like `expr = a`,
    `expr = b`, etc..., it is advantageous to provide a Dummy symbol
    for `rhs` and  simply replace it with `a`, `b`, etc... in `r`.

    >>> rhs = Dummy('rhs')
    >>> clear_coefficients(expr, rhs)
    (y*(2*x + 1), _rhs/12)
    >>> _[1].subs(rhs, 2)
    1/6
    NTr   Fr   )
rt   rY  r   r   r   r   r~   as_coeff_Addr   r   )r]   rhswasfreery  r   s         ra   clear_coefficientsr  1  s    6 CDd
##
3$;  %%'++T+: 	4 	q##T#24q 3$; DU+D$$&ud9rc   c           	        #$%& t        | t              r.| j                  d      } t        t        t
        t        f\  #$%}nt        t        t        t        f\  #$%}d }$%fd}#$%&fd&&fd}t        | #$%f      r| j                  r| S | j                  dd }t        | %      r*|r& %t        |d         |d	         j                         S | S t        | #      r, #|D cg c]  }t        ||
       c} j                         S | j                         \  }}t        | }	|	d	k7  r|	t        | |	z  |
      z  S  ||      \  }
}d}|
t        |      dz  kD  rd}|ddd   D cg c]  }|dz  	 }}|rt!        d |D              } ||      }i }d	}d	}d}d}t#        d	t        |            D ]  }d}d}d}|t        |      d	z
  k  r||   d   }|}|d	z   }|t        |      d	z
  k(  sdgk(  rt        ||   %      rst        ||   j                  d   |      sW||   j                  d   j                  }t        |      }|||z
  | |k(  r
|d	z  }||z  }||d	z   |d	z   |z    |k(  r
|d	z  }||z  }|r|||   j                  d	   z  }n|d   }||d	z
  z  }||| }d}||z  }|v r
||   |k\  r|t        |      k  rq|||d	z
     d   v r|d	z  }||z  }nJt        ||   %      r:||   j                  d   j                  |k(  r|||   j                  d	   z  }|d	z  }nn|t        |      k  rqd}d	}||z
  dk\  r|||z
  d	z   | |d	d k(  rt        |d   %      r%|d   j                  d   }|d   j                  d	   }n|d   }d	}t        |||z
     %      r;|||z
     j                  d   |k(  r#|||z
     j                  d	   |z
  }||z  }|d	z  }n|||z
     |k(  rd	|z
  }||z  }|d	z  }d}d	}||z   d	z
  t        |      k  r||||z   d	z
   |dd k(  rt        |d   %      r%|d   j                  d   }|d   j                  d	   }n|d   }d	}t        |||z   d	z
     %      rA|||z   d	z
     j                  d   |k(  r&|||z   d	z
     j                  d	   |z
  }||z  }|d	z  }n|||z   d	z
     |k(  rd	|z
  }||z  }|d	z  }|rdz  dk(  r|dkD  r|dz  }d	}d	} t        ||d	z
     %      r6||d	z
     j                  d   |k(  r||z   } ||d	z
     j                  d	   |z
  }n||d	z
     |k(  r
||z   } d	|z
  }|dk(  s| dk(  r |s|d	z  }| }|}|}||z  f|dd z   ||z  fz   }|||z
  z  }|r|d	z  }|r|d	z  }|||<   ||kD  s|}| $| |||f}||z  }||z  } |rl %t        |d	   |
      |d         }t         $|d|d     |z  |
      }|t         $||d   d  |
      z  }||z  |z  }|d	k7  s|d	k7  rt        |d
      }n $| }|r	 %|d      }t        | t              s(t%        |       }!|!| k7  rt        |!|
      }" |||"      }|S |j                  d      }|S c c}w c c}w )a  
    Simplify a non-commutative expression composed of multiplication
    and raising to a power by grouping repeated subterms into one power.
    Priority is given to simplifications that give the fewest number
    of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying
    to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3).
    If ``expr`` is a sum of such terms, the sum of the simplified terms
    is returned.

    Keyword argument ``deep`` controls whether or not subexpressions
    nested deeper inside the main expression are simplified. See examples
    below. Setting `deep` to `False` can save time on nested expressions
    that do not need simplifying on all levels.

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.simplify.simplify import nc_simplify
    >>> a, b, c = symbols("a b c", commutative=False)
    >>> nc_simplify(a*b*a*b*c*a*b*c)
    a*b*(a*b*c)**2
    >>> expr = a**2*b*a**4*b*a**4
    >>> nc_simplify(expr)
    a**2*(b*a**4)**2
    >>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2)
    ((a*b)**2*c**2)**2
    >>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a)
    (a*b)**2 + 2*(a*c*a)**3
    >>> nc_simplify(b**-1*a**-1*(a*b)**2)
    a*b
    >>> nc_simplify(a**-1*b**-1*c*a)
    (b*a)**(-1)*c*a
    >>> expr = (a*b*a*b)**2*a*c*a*c
    >>> nc_simplify(expr)
    (a*b)**4*(a*c)**2
    >>> nc_simplify(expr, deep=False)
    (a*b*a*b)**2*(a*c)**2

    F)
inv_expandc                    | dd  D cg c]  }|| d   k(  rddgndg c}g}t        dt        |             D ]  }g }d}t        t        |       |z
  dz
        D ]o  }g }||dz
     |dz      D ]C  }||z   dz   |z   t        |       k  s| |   | ||z   dz   |z      k(  s0|j                  |dz          E |dgz  }|j                  |       q |j                  |        |S c c}w )Nrk   r   )r  rs   r   )rm   r   ry  r   overlapsr"  overlapr   s           ra   	_overlapsznc_simplify.<locals>._overlaps  s    :>abBAd1g1vA3.BCq#d)$ 
	AHA3t9q=1,- )1Q3! .A1uqy1}s4y0T!WQqSU1W5Mq1u-. A3() HHX
	  Cs   Cc                    d}g }g }| D ]  }t        |      r(|j                  d   j                  r|dz  g|z   }|dz  }7t        |      dk(  r|j	                  |d   dz         n:t        |      dkD  r,|j	                    | d             |t        |      dz
  z  }g }|j	                  |        |r,|j	                    | d             |t        |      dz
  z  }|t        |      fS )Nr   rk   r   )rl   rm   is_extended_negativers   r   rZ  )_argsinv_totinversesrm   r   _Mul_Pows        ra   _reduce_inversesz%nc_simplify.<locals>._reduce_inverses  s      	!C#t$!)I)IG9x/1x=A%KKR0]Q&KKT8_b 9:s8}q00GC 	! KKT8_b12s8}q((Gd##rc   c                     t        |       r | j                  d         S t        | f      r)t        | j                  D cg c]
  } |       c}      S yc c}w )Nr   rk   )rl   rm   sum)r   r   _Addr  r  	get_scores     ra   r  znc_simplify.<locals>.get_score  sV     aQVVAY''D$<(aff5	!566 6s   Ac                 8    | |k7  r |       |       k  r|S | S r   r   )r   alt_sr  s     ra   compareznc_simplify.<locals>.compare  s&     :)E*Yq\9Lrc   Nr   rk   r   re   Tr   c              3   2   K   | ]  }t        |        y wr   )r   )r   r   s     ra   r   znc_simplify.<locals>.<genexpr>  s     2[^2s      )rl   r?   r   r@   rA   rB   rC   r   r	   r
   r   r   rm   r   r}   rs   rZ  r  r   )'r]   r   _Symbolr  r  r  rm   r   c_args	com_coeffr  invertry  simpspostpremax_simp_coeffsimpr   
simp_coeffrU  rH  repstartendsubtermpre_exppre_argr'   post_exppost_arg_pre_exp	_post_expf_expralt_simpr  r  r  r  s'                                      @@@@ra   r   r   _  s   R $
#yyEy*$*FFL$H!dD'$'c6$9!dD'0$4 dT4./43F3F99Q<D$DG,d1g6;;==K	D$	>Ak!$/>?DDFF }}L	>[idCCC$T*MGT FT1#DbDz*!2**2T22$A ED
C ND1c$i  F&
s4y1}A$q'CcD	!sqcz 47D) *47<<?G Dq',,q/..L!A;') FAQJE!AaCE?g-FA1HCT!W\\!_$AAQUNE5oGA1HCeg% 7  CIoAc!eHQKQqDIt,c1B1G1G71RT#Y^^A&&q CIo 19>d5719U3wqr{B'!*d+!!*//!,ajooa(!!*$uQw-.4a=3E3Ea3HG3SuQw-,,Q/#5
QeAg')c'
Q7Q;T"tCAa'8GCRL'H'"+t,"2;++A.bk&&q)"2;$s1uQw-.4Aa=3E3Ea3HH3TAa=--a036qQc!eAg(*s7qQ a1a%CHI$uQw-.4a=3E3Ea3HH3T$sN	a=--a036eAg(*$sN	s71}	QQJE$""#S=*WSb\9Xs]<LLc%i
!OJ!OJg&'N4>1c15D7"CX%DMF&P {476Q@$Xd1g/3$?Kd478n 5DAA7{4!8tqy t%0DT{D"~ dJ'4T>"65H4*D K yyEy*KQ ? +s   (Y0+Y5c           
         d }fdd}t        | t              r| j                  s| j                  s| j                  r| j                  dddddddd      }|| k7  r|} d} ||       \  }}|dk\  rj|ri } | |      }|| u s ||      d   dk\  rht        |      }||k7  rW|j                  |j                         D 	
cg c]	  \  }	}
|
|	f c}
}	      } d}n|d	k(  r| j                  r
| j                  d   j                  r| j                  d
   j                  r| j                  d   j                  d   j                  r| j                  d
   j                  d   j                  r| j                  d   j                  d   j                  t        j                  u rV| j                  d
   j                  d   j                  t        j                  u r t        |       } ||      d   }||k  r|} d}nd}|r| |fS | S c c}
}	w )a  Simplification for a sum of products targeted at the kind of blowup that
    occurs during summation of products. Intended to reduce expression blowup
    during matrix multiplication or other similar operations. Only works with
    algebraic expressions and does not recurse into non.

    Parameters
    ==========

    withsimp : bool, optional
        Specifies whether a flag should be returned along with the expression
        to indicate roughly whether simplification was successful. It is used
        in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to
        simplify an expression repetitively which does not simplify.
    c                    d}| g}d}|rA|j                         }t        |t              s$|j                  rI|t        j
                  ur|t        |j                  dk        t        |j                  dk7        z   z  }n|j                  r|j                         r;|dz  }|j                  d   t        j                  u r|j                         d   }n| }t        |      \  }}|j                  r'|dt        |dk        z   z  }|j!                  |       n.|t        j
                  ur6|j                  s|j!                  |       d}|dz  }|j!                  |       n|t#        |j                        dz
  z  }|j%                  |j                         n|j&                  r]t#        |j                        }d}|j                  D ]+  }	|	j                         r|dz  }|	 }	|j!                  |	       - ||||k7  z
  z  }nF|j(                  r:|dz  }|j!                  |j*                         |s|j,                  j.                  du}|rA||fS )aj  Optimized count algebraic operations with no recursion into
        non-algebraic args that ``core.function.count_ops`` does. Also returns
        whether rational functions may be present according to negative
        exponents of powers or non-number fractions.

        Returns
        =======

        ops, ratfunc : int, bool
            ``ops`` is the number of algebraic operations starting at the top
            level expression (not recursing into non-alg children). ``ratfunc``
            specifies whether the expression MAY contain rational functions
            which ``cancel`` MIGHT optimize.
        r   Frk   T)r   rl   r   rY  r   r  boolrH  qrn   r   rm   r   as_two_termsrO   r  r   rs   extendr|   rw   rx   r'   is_negative)
r]   opsrm   ratfuncr   r  r  laargsnegsr`  s
             ra   count_ops_algz"dotprodsimp.<locals>.count_ops_alg  s     &
Aa'}}AEE>4q>D!##(O;;C--/1HCvvayAMM1NN,Q/B{1<<1tQU|++CKKNaee^<<A $1HCKKN 3qvv;?*CKK'QVV&& $B224	!#KKO	$ v00qAFF#ee//u<Gk n G|rc   c                 T   | j                   s| S | j                  s| j                  s| j                  r\d}t	        | j                         D ]/  \  }} ||      }||u r|t        | j                         }|||<   1 || S  | j                  | S |j                  | t                     S )zSubstitute dummy variables for non-algebraic expressions to avoid
        evaluation of non-algebraic terms that ``polys.polytools.cancel`` does.
        N)	rm   r|   rn   rw   rv   ru   rq   
setdefaultr   )r]   dummiesrm   r   r   r   nonalg_subs_dummiess         ra   r#  z(dotprodsimp.<locals>.nonalg_subs_dummies  s    
 yyK;;$++D!$)), 	1'736<		?DQ	 |499d##!!$00rc   FTN)r   modulus
power_base	power_exprg   r)   rh   r      r      rk   r   )rl   r   r|   rn   rw   r   rE   r{   r   rm   r'   r   r   rD   )r]   withsimpr  
simplifiedr	  expropsr  r"  expr3r   r  expr2opsr#  s               @ra   dotprodsimpr.    s    KZ1: J$DKK4;;$++t5d%  Q D=DJ(.a<-dG<D=M%$8$;q$@"5ME~%*ZZGMMO0TDAq!Q0T%U%)
 lt{{tyy!}/C/C		1$$A););R)@)G)G		1""B'..		1""B'++q}}<		1""B'++q}}<E$U+A.H'!"!
 J!)D*3t3) 1Us   H
z
    Using bottom_up from the sympy.simplify.simplify submodule is
    deprecated.

    Instead, use bottom_up from the top-level sympy namespace, like

        sympy.bottom_up
    z1.10z$deprecated-traversal-functions-moved)deprecated_since_versionactive_deprecations_targetz
    Using walk from the sympy.simplify.simplify submodule is
    deprecated.

    Instead, use walk from sympy.core.traversal.walk
    r   )NFFFT)r   )F)   r  )r   NFNr  )Nr  )T)collectionsr   sympy.concrete.productsr   sympy.concrete.summationsr   
sympy.corer   r   r   r	   r
   r   r   r   r   r   r   r   r   r   sympy.core.exprtoolsr   sympy.core.parametersr   sympy.core.functionr   r   r   r   r   r   sympy.core.numbersr   r   r   r   sympy.core.relationalr    sympy.core.rulesr!   sympy.core.sortingr"   sympy.core.sympifyr#   sympy.core.traversalr$   r   r%   _walksympy.functionsr&   r'   r(   r)   r*   r+   (sympy.functions.combinatorial.factorialsr,   $sympy.functions.elementary.complexesr-   r.   r/   &sympy.functions.elementary.exponentialr0   %sympy.functions.elementary.hyperbolicr1   #sympy.functions.elementary.integersr2   $sympy.functions.elementary.piecewiser3   r4   r5   (sympy.functions.elementary.trigonometricr6   sympy.functions.special.besselr7   r8   r9   r:   r;   r<   (sympy.functions.special.tensor_functionsr=   sympy.integrals.integralsr>   sympy.matrices.expressionsr?   r@   rA   rB   rC   sympy.polysrD   rE   rF    sympy.polys.numberfields.minpolyrG   rH   sympy.simplify.combsimprI   sympy.simplify.cse_optsrJ   rK   sympy.simplify.hyperexpandrL   sympy.simplify.powsimprM   sympy.simplify.radsimprN   rO   rP   sympy.simplify.sqrtdenestrQ   sympy.simplify.trigsimprR   rS   sympy.utilities.decoratorrT   sympy.utilities.iterablesrU   rV   rW   rX   sympy.utilities.miscrY   r  rb   r\   r[   rz   r   r   r   r   r   r  r+  r  r   r<  rM  r   r   r   r   r  r   r  r   r  r   r.  r   rc   ra   <module>rX     s   # + ). . . . + 3    5 5 , & & ' G @ @ J F F : D 7F F JB B C .B B 0 0 R , 5 2 * A A 0 9 0 J J '   "U G*T=@@:/z,^%,DN i%UY Tn
66(2)X#L20M`#L0fpf9x HL HLV>+B "# ,\EP
c4LJ $E 	 	z $E	 		rc   