Question: sylowsubgroup() IndexError I use sympy 1.6.1, with numpy 1.18.5, scipy 1.4.1, under Python '3.8.5 (default, Aug 5 2020, 09:44:06) [MSC v.1916 64 bit (AMD64)]'. The code that I run as the following gives IndexError for sylowsubgroup(): from sympy.combinatorics import DihedralGroup, PermutationGroup, Permutation G = DihedralGroup(18) S2 = G.sylowsubgroup(p=2) Traceback (most recent call last): File "<input", line 7, in <moduleFile "D:\anaconda38\envs\default\lib\site-packages\sympy\combinatorics\", line 4370, in sylowsubgroup blocks = self.minimalblocks() File "D:\anaconda38\envs\default\lib\site-packages\sympy\combinatorics\", line 2207, in minimalblocks del numblocks[i], blocks[i] IndexError: list assignment index out of range The same error shows up as well when I set: G = DihedralGroup(2*25) S2 = G.sylowsubgroup(p=2)

# check if the system is minimal with                 # respect to the already discovere ones                 minimal = True                to_remove = []                blocks_remove_mask = [False] * len(blocks)                 for i, r in enumerate(rep_blocks):                     if len(r) > len(rep) and rep.issubset(r):                         # i-th block system is not minimal                        del num_blocks[i], blocks[i]                        to_remove.append(rep_blocks[i])                        blocks_remove_mask[i] = True                     elif len(r) < len(rep) and r.issubset(rep):                         # the system being checked is not minimal                         minimal = False                         break                 # remove non-minimal representative blocks                rep_blocks = [r for r in rep_blocks if r not in to_remove]                blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]]                num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]]                rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]]                  if minimal and num_block not in num_blocks:                     blocks.append(block)


Question: () should calculate the velocity if possible If you specify the orientation of two reference frames and then ask for the angular velocity between the two reference frames the angular velocity will be calculated. But if you try to do the same thing with velocities, this doesn't work. See below: The expected result of the should be: I think that this is possible. Maybe there is a reason it isn't implemented. But we should try to implement it because it is confusing why this works for orientations and not positions.

Examples         ========         >>> from sympy.physics.vector import Point, ReferenceFrame        >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols         >>> N = ReferenceFrame('N')         >>> p1 = Point('p1')         >>> p1.set_vel(N, 10 * N.x)         >>> p1.vel(N)         10*N.x         Velocities will be automatically calculated if possible, otherwise a ``ValueError`` will be returned. If it is possible to calculate multiple different velocities from the relative points, the points defined most directly relative to this point will be used. In the case of inconsistent relative positions of points, incorrect velocities may be returned. It is up to the user to define prior relative positions and velocities of points in a self-consistent way.        >>> p = Point('p')        >>> q = dynamicsymbols('q')        >>> p.set_vel(N, 10 * N.x)        >>> p2 = Point('p2')        >>> p2.set_pos(p, q*N.x)        >>> p2.vel(N)        (Derivative(q(t), t) + 10)*N.x         """          _check_frame(frame)         if not (frame in self._vel_dict):            raise ValueError('Velocity of point ' + self.name + ' has not been'            visited = []            queue = [self]            while queue: #BFS to find nearest point                node = queue.pop(0)                if node not in visited:                    visited.append(node)                    for neighbor, neighbor_pos in node._pos_dict.items():                        try:                            neighbor_pos.express(frame) #Checks if pos vector is valid                        except ValueError:                            continue                        try :                            neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame                        except KeyError:                            queue.append(neighbor)                            continue                        self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                        return self._vel_dict[frame]            else:                raise ValueError('Velocity of point ' + self.name + ' has not been'                              ' defined in ReferenceFrame ' + frame.name)         return self._vel_dict[frame]      def partial_velocity(self, frame, *gen_speeds):


Question: Lambdify does not identify frac() Hello, this is my first issue ever. The following code gives the following error If there exists a fix, please let me know. Replacing () with just frac() does not help either.

def _print_NoneToken(self, arg):         return 'None' <del>class PythonCodePrinter(AbstractPythonCodePrinter):    def _print_sign(self, e):        return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(            f=self._module_format('math.copysign'), e=self._print(e.args[0]))    def _print_Not(self, expr):        PREC = precedence(expr)        return self._operators['not'] + self.parenthesize(expr.args[0], PREC)    def _print_Indexed(self, expr):        base = expr.args[0]        index = expr.args[1:]        return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))</del>     def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'):         """Printing helper function for ``Pow``


Question: Lambdify does not identify frac() Hello, this is my first issue ever. The following code gives the following error If there exists a fix, please let me know. Replacing () with just frac() does not help either.

exp_str = self.parenthesize(expr.exp, PREC, strict=False)         return "{}**{}".format(base_str, exp_str) <ins>class PythonCodePrinter(AbstractPythonCodePrinter):    def _print_sign(self, e):        return '(0.0 if {e} == 0 else {f}(1, {e}))'.format(            f=self._module_format('math.copysign'), e=self._print(e.args[0]))    def _print_Not(self, expr):        PREC = precedence(expr)        return self._operators['not'] + self.parenthesize(expr.args[0], PREC)    def _print_Indexed(self, expr):        base = expr.args[0]        index = expr.args[1:]        return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index]))</ins>     def _print_Pow(self, expr, rational=False):         return self._hprint_Pow(expr, rational=rational)


Question: Lambdify does not identify frac() Hello, this is my first issue ever. The following code gives the following error If there exists a fix, please let me know. Replacing () with just frac() does not help either.

def _print_Half(self, expr):         return self._print_Rational(expr) <ins>    def _print_frac(self, expr):        from sympy import Mod        return self._print_Mod(Mod(expr.args[0], 1))</ins>     _print_lowergamma = CodePrinter._print_not_supported     _print_uppergamma = CodePrinter._print_not_supported     _print_fresnelc = CodePrinter._print_not_supported


Question: Lambdify does not identify frac() Hello, this is my first issue ever. The following code gives the following error If there exists a fix, please let me know. Replacing () with just frac() does not help either.

_in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] _known_functions_mpmath = dict(_in_mpmath, **{     'beta': 'beta',<ins>    'frac': 'frac',</ins>     'fresnelc': 'fresnelc',     'fresnels': 'fresnels',     'sign': 'sign',


Question: Lambdify does not identify frac() Hello, this is my first issue ever. The following code gives the following error If there exists a fix, please let me know. Replacing () with just frac() does not help either.

setattr(SciPyPrinter, '_print_%s' % k, _print_known_const)  class SymPyPrinter(PythonCodePrinter):class SymPyPrinter(AbstractPythonCodePrinter):      language = "Python with SymPy"     _kf = {k: 'sympy.' + v for k, v in chain(        _known_functions.items(),        _known_functions_math.items()    )}     def _print_Function(self, expr):         mod = expr.func.__module__ or ''         return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__),


Question: Warn the user when trees of points or trees of reference frames are not self consistent. has Point and ReferenceFrame. These can be positioned and oriented relative to objects of their same type, respectively. The user is expected to define relative positions and orientations in a consistent manner and the relationships among the objects should be tree graphs. It would be helpful to warn the user if they set positions and orientations that create incorrect graphs, for example adding a cyclic branch; the graphs should be acyclic. You can also create inconsistencies when it comes to calculating velocities and angular velocities, which is done automatically if possible. Here is a point example: The velocities of O in N are different depending on if you calculate based on P or Q. It is also impossible to choose between P or Q. Right now, P or Q will be chosen based on which comes first in . We should warn the user that this graph is inconsistent when trying to calculate the velocity of O in N. This same thing can happen with ReferenceFrame. I suspect there will be issues when users have kinematic loops and may want to define the loop of point positions that specify the loop. Currently, that is not supported. If you specify a loop through a succession of setpos() or locatenew() calls, you get an invalid point tree. Kinematic loops have to be dealt with by adding the algebraic equation and forming DAEs instead. These warnings need some careful thought. The first step would be to define precisely what graphs are consistent and non consistent, in terms of 's capabilities and design. Once that is defined, some methods to check for consistencies can be . There will be inconsistencies related purely to position and orientation as well as inconsistencies related to the automated calculation of velocities. There is discussion in this PR that is relevant:

from __future__ import print_function, division from .vector import Vector, _check_vector from .frame import _check_frame<ins>from warnings import warn</ins>  __all__ = ['Point']


Question: Warn the user when trees of points or trees of reference frames are not self consistent. has Point and ReferenceFrame. These can be positioned and oriented relative to objects of their same type, respectively. The user is expected to define relative positions and orientations in a consistent manner and the relationships among the objects should be tree graphs. It would be helpful to warn the user if they set positions and orientations that create incorrect graphs, for example adding a cyclic branch; the graphs should be acyclic. You can also create inconsistencies when it comes to calculating velocities and angular velocities, which is done automatically if possible. Here is a point example: The velocities of O in N are different depending on if you calculate based on P or Q. It is also impossible to choose between P or Q. Right now, P or Q will be chosen based on which comes first in . We should warn the user that this graph is inconsistent when trying to calculate the velocity of O in N. This same thing can happen with ReferenceFrame. I suspect there will be issues when users have kinematic loops and may want to define the loop of point positions that specify the loop. Currently, that is not supported. If you specify a loop through a succession of setpos() or locatenew() calls, you get an invalid point tree. Kinematic loops have to be dealt with by adding the algebraic equation and forming DAEs instead. These warnings need some careful thought. The first step would be to define precisely what graphs are consistent and non consistent, in terms of 's capabilities and design. Once that is defined, some methods to check for consistencies can be . There will be inconsistencies related purely to position and orientation as well as inconsistencies related to the automated calculation of velocities. There is discussion in this PR that is relevant:

_check_frame(frame)         if not (frame in self._vel_dict):            valid_neighbor_found = False            is_cyclic = False             visited = []             queue = [self]            candidate_neighbor = []             while queue: #BFS to find nearest point                 node = queue.pop(0)                 if node not in visited:                     visited.append(node)                     for neighbor, neighbor_pos in node._pos_dict.items():                        if neighbor in visited:                            continue                         try:                             neighbor_pos.express(frame) #Checks if pos vector is valid                         except ValueError:                             continue                        if neighbor in queue:                            is_cyclic = True                         try :                             neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame                         except KeyError:                             queue.append(neighbor)                             continue                        self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                        return self._vel_dict[frame]                        candidate_neighbor.append(neighbor)                        if not valid_neighbor_found:                            self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity)                            valid_neighbor_found = True            if is_cyclic:                warn('Kinematic loops are defined among the positions of points. This is likely not desired and may cause errors in your calculations.')            if len(candidate_neighbor) > 1:                warn('Velocity automatically calculated based on point ' +                    candidate_neighbor[0].name + ' but it is also possible from points(s):' +                    str(candidate_neighbor[1:]) + '. Velocities from these points are not necessarily the same. This may cause errors in your calculations.')            if valid_neighbor_found:                return self._vel_dict[frame]             else:                 raise ValueError('Velocity of point ' + self.name + ' has not been'                              ' defined in ReferenceFrame ' + frame.name)


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

def _hashable_content(self):         return (self.name,)  def _filter_assumptions(kwargs):     """Split the given dict into assumptions and non-assumptions.     Keys are taken as assumptions if they correspond to andiff --git a/sympy/matrices/expressions/matexpr.py b/sympy/matrices/expressions/matexpr.py-- a/sympy/matrices/expressions/matexpr.py++ b/sympy/matrices/expressions/matexpr.py


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

from sympy.core import S, Symbol, Integer, Basic, Expr, Mul, Add from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import SYMPY_INTS, default_sort_key<ins>from sympy.core.symbol import Str</ins> from sympy.core.sympify import SympifyError, _sympify from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

cls._check_dim(n)          if isinstance(name, str):            name = Symbol(name)            name = Str(name)         obj = Basic.__new__(cls, name, n, m)         return obj diff --git a/sympy/printing/dot.py b/sympy/printing/dot.py-- a/sympy/printing/dot.py++ b/sympy/printing/dot.py


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

>>> from sympy import Float, Symbol, MatrixSymbol     >>> from sympy import Integer # noqa: F401<ins>    >>> from sympy.core.symbol import Str # noqa: F401</ins>     >>> from sympy.printing.dot import purestr      Applying ``purestr`` for basic symbolic object:


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

For matrix symbol:     >>> code = purestr(MatrixSymbol('x', 2, 2))     >>> code    "MatrixSymbol(Symbol('x'), Integer(2), Integer(2))"    "MatrixSymbol(Str('x'), Integer(2), Integer(2))"     >>> eval(code) == MatrixSymbol('x', 2, 2)     True


Question: Use Str instead of Symbol for name of MatrixSymbol <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --<!-- If this pull request fixes an issue, write "Fixes #NNNN" in that exact format, e.g. " (see for more information). Also, please write a comment on that issue linking back to this pull request once it is open. --<!-- Write the release notes for this release below. See for more information on how to write release notes. The bot will check your release notes automatically to see if they are formatted correctly. --<!-- BEGIN RELEASE NOTES --- matrices will store Str in its first argument. <!-- END RELEASE NOTES --

>>> purestr(Float(2), with_args=True)     ("Float('2.0', precision=53)", ())     >>> purestr(MatrixSymbol('x', 2, 2), with_args=True)    ("MatrixSymbol(Symbol('x'), Integer(2), Integer(2))",     ("Symbol('x')", 'Integer(2)', 'Integer(2)'))    ("MatrixSymbol(Str('x'), Integer(2), Integer(2))",     ("Str('x')", 'Integer(2)', 'Integer(2)'))     """     sargs = ()     if not isinstance(x, Basic):


Question: partitions() reusing the output dictionaries The partitions() iterator in sympy.utilities.iterables reuses the output dictionaries. There is a caveat about it in the docstring. I'm wondering if it's really that important for it to do this. It shouldn't be that much of a performance loss to copy the dictionary before yielding it. This behavior is very confusing. It means that something as simple as list(partitions()) will give an apparently wrong result. And it can lead to much more subtle bugs if the partitions are used in a nontrivial way.

{2: 1, 4: 1}     {3: 2} <del>    Note that the _same_ dictionary object is returned each time.    This is for speed:  generating each partition goes quickly,    taking constant time, independent of n.    >>> [p for p in partitions(6, k=2)]    [{1: 6}, {1: 6}, {1: 6}, {1: 6}]    If you want to build a list of the returned dictionaries then    make a copy of them:    >>> [p.copy() for p in partitions(6, k=2)]  # doctest: +SKIP    [{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]    >>> [(M, p.copy()) for M, p in partitions(6, k=2, size=True)]  # doctest: +SKIP    [(3, {2: 3}), (4, {1: 2, 2: 2}), (5, {1: 4, 2: 1}), (6, {1: 6})]</del>     References     ==========


Question: partitions() reusing the output dictionaries The partitions() iterator in sympy.utilities.iterables reuses the output dictionaries. There is a caveat about it in the docstring. I'm wondering if it's really that important for it to do this. It shouldn't be that much of a performance loss to copy the dictionary before yielding it. This behavior is very confusing. It means that something as simple as list(partitions()) will give an apparently wrong result. And it can lead to much more subtle bugs if the partitions are used in a nontrivial way.

keys.append(r)     room = m - q - bool(r)     if size:        yield sum(ms.values()), ms        yield sum(ms.values()), ms.copy()     else:        yield ms        yield ms.copy()      while keys != [1]:         # Reuse any 1's.


Question: partitions() reusing the output dictionaries The partitions() iterator in sympy.utilities.iterables reuses the output dictionaries. There is a caveat about it in the docstring. I'm wondering if it's really that important for it to do this. It shouldn't be that much of a performance loss to copy the dictionary before yielding it. This behavior is very confusing. It means that something as simple as list(partitions()) will give an apparently wrong result. And it can lead to much more subtle bugs if the partitions are used in a nontrivial way.

break         room -= need         if size:            yield sum(ms.values()), ms            yield sum(ms.values()), ms.copy()         else:            yield ms            yield ms.copy()   def ordered_partitions(n, m=None, sort=True):


Question: Lens makers formula Currently lens maker formula is limited to thin lens. It should also work for plano- lenses(plano-concave and plano convex) and thick lens.

]  from sympy import Symbol, sympify, sqrt, Matrix, acos, oo, Limit, atan2, asin,\cos, sin, tan, I, cancel, pi, Floatcos, sin, tan, I, cancel, pi, Float, S, zoo from sympy.core.compatibility import is_sequence from sympy.geometry.line import Ray3D from sympy.geometry.util import intersection


Question: Lens makers formula Currently lens maker formula is limited to thin lens. It should also work for plano- lenses(plano-concave and plano convex) and thick lens.

def lens_makers_formula(n_lens, n_surr, r1, r2):def lens_makers_formula(n_lens, n_surr, r1, r2, d=0):     """    This function calculates focal length of a thin lens.    This function calculates focal length of a lens.     It follows cartesian sign convention.      Parameters


Question: Lens makers formula Currently lens maker formula is limited to thin lens. It should also work for plano- lenses(plano-concave and plano convex) and thick lens.

Radius of curvature of first surface.     r2 : sympifiable         Radius of curvature of second surface.    d : sympifiable, optional        Thickness of lens, default value is 0.      Examples     ========      >>> from sympy.physics.optics import lens_makers_formula    >>> from sympy import S     >>> lens_makers_formula(1.33, 1, 10, -10)     15.1515151515151    >>> lens_makers_formula(1.2, 1, 10, S.Infinity)    50.0000000000000    >>> lens_makers_formula(1.33, 1, 10, -10, d=1)    15.3418463277618      """     if isinstance(n_lens, Medium):         n_lens = n_lens.refractive_index     else:


Question: Lens makers formula Currently lens maker formula is limited to thin lens. It should also work for plano- lenses(plano-concave and plano convex) and thick lens.

n_surr = n_surr.refractive_index     else:         n_surr = sympify(n_surr)    d = sympify(d)     r1 = sympify(r1)    r2 = sympify(r2)    focal_length = 1/((n_lens - n_surr) / n_surr*(1/r1 - 1/r2 + (((n_lens - n_surr) * d) / (n_lens * r1 * r2))))     return 1/((n_lens - n_surr)/n_surr*(1/r1 - 1/r2))    if focal_length == zoo:        return S.Infinity    return focal_length   def mirror_formula(focal_length=None, u=None, v=None):


Question: 0-oo produces 0, the documentation says it should produce zoo Using SymPy 1.5.1, evaluate produces . The documentation for the Pow class states that it should return , aka

).warn()          if evaluate:<ins>            if b is S.Zero and e is S.NegativeInfinity:                return S.ComplexInfinity</ins>             if e is S.ComplexInfinity:                 return S.NaN             if e is S.Zero:


Question: RecursionError occured while convert sympy expression to latex when expression like Pow(1/n,-1) Hello, Thanks for awesome library :) I find issue but I can't figure out why the following phenomena occur, so I write an issue. I use and i tried to latex function to change sympy expression to latex. But RecursionError occured while change Pow(Rational(1,n), evaluate=False) result to latex. It error occured only when (numerator = 1 and denominator=Positive integer bigger than 1) or (numerator = -1 and denominator=Negative integer lower than -1) . Below is code of i runned:

# special case for 1^(-x), issue 9216             if expr.base == 1:                 return r"%s^{%s}" % (expr.base, expr.exp)<ins>            # special case for (1/x)^(-y) and (-1/-x)^(-y), issue 20252            if expr.base.is_Rational and \                    expr.base.p*expr.base.q == abs(expr.base.q):                if expr.exp == -1:                    return r"\frac{1}{\frac{%s}{%s}}" % (expr.base.p, expr.base.q)                else:                    return r"\frac{1}{(\frac{%s}{%s})^{%s}}" % (expr.base.p, expr.base.q, abs(expr.exp))</ins>             # things like 1/x             return self._print_Mul(expr)         else:


Question: Inconsistent behavior for sympify/simplify with ceiling In sympy v1.5.1: In sympy v.1.6.2: Is there a way to ensure that the behavior is consistent, even though evaluate is equal to when parsing?

from .singleton import S from .operations import AssocOp, AssocOpDispatcher from .cache import cacheitfrom .logic import fuzzy_not, _fuzzy_group, fuzzy_andfrom .logic import fuzzy_not, _fuzzy_group from .compatibility import reduce from .expr import Expr from .parameters import global_parameters


Question: Inconsistent behavior for sympify/simplify with ceiling In sympy v1.5.1: In sympy v.1.6.2: Is there a way to ensure that the behavior is consistent, even though evaluate is equal to when parsing?

zero = None         return zero     # without involving odd/even checks this code would suffice:    #_eval_is_integer = lambda self: _fuzzy_group(    #    (a.is_integer for a in self.args), quick_exit=True)     def _eval_is_integer(self):        from sympy import fraction        from sympy.core.numbers import Float         is_rational = self._eval_is_rational()         if is_rational is False:             return False         # use exact=True to avoid recomputing num or den        n, d = fraction(self, exact=True)        if is_rational:            if d is S.One:                return True        if d.is_even:            if d.is_prime:  # literal or symbolic 2                return n.is_even            if n.is_odd:                return False  # true even if d = 0        if n == d:            return fuzzy_and([not bool(self.atoms(Float)),            fuzzy_not(d.is_zero)])        numerators = []        denominators = []        for a in self.args:            if a.is_integer:                numerators.append(a)            elif a.is_Rational:                n, d = a.as_numer_denom()                numerators.append(n)                denominators.append(d)            elif a.is_Pow:                b, e = a.as_base_exp()                if not b.is_integer or not e.is_integer: return                if e.is_negative:                    denominators.append(b)                else:                    # for integer b and positive integer e: a = b**e would be integer                    assert not e.is_positive                    # for self being rational and e equal to zero: a = b**e would be 1                    assert not e.is_zero                    return # sign of e unknown -> self.is_integer cannot be decided            else:                return        if not denominators:            return True        odd = lambda ints: all(i.is_odd for i in ints)        even = lambda ints: any(i.is_even for i in ints)        if odd(numerators) and even(denominators):            return False        elif even(numerators) and denominators == [2]:            return True      def _eval_is_polar(self):         has_polar = any(arg.is_polar for arg in self.args)


Question: Result from cleardenoms() prints like zero poly but behaves wierdly (due to unstripped DMP) The was the immediate cause of the ZeroDivisionError in . Calling on a complicated constant poly that turns out to be zero: The result prints like the zero polynomial but behaves inconsistently: ( points out this is a bug in ), but other Poly methods don't handle very well. e.g. Also sometime in the last year Poly.primitive has been changed to slightly better handle this bad poly. but in earlier versions of SymPy: which was the cause of the ZeroDivisionError reported in . Looking at the underlying DMP, there is an unstripped leading 0 in the list representation of the Poly which should be

return not f == g          def __bool__(f):            return f.ex != 0            return not f.ex.is_zero          def gcd(f, g):             from sympy.polys import gcd


Question: convertto seems to combine orthogonal units Tested in sympy 1.4, not presently in a position to install 1.5+. Simple example. Consider . The convertto behavior is odd: I would expect the unchanged original expression back, an expression in terms of base units, or an error. It appears that convert_to can only readily handle conversions where the full unit expression is valid. Note that the following three related examples give sensible results:

from sympy import Add, Mul, Pow, Tuple, sympify from sympy.core.compatibility import reduce, Iterable, ordered<ins>from sympy.matrices.common import NonInvertibleMatrixError</ins> from sympy.physics.units.dimensions import Dimension from sympy.physics.units.prefixes import Prefix from sympy.physics.units.quantities import Quantity


Question: convertto seems to combine orthogonal units Tested in sympy 1.4, not presently in a position to install 1.5+. Simple example. Consider . The convertto behavior is odd: I would expect the unchanged original expression back, an expression in terms of base units, or an error. It appears that convert_to can only readily handle conversions where the full unit expression is valid. Note that the following three related examples give sensible results:

camat = Matrix([[dimension_system.get_dimensional_dependencies(i, mark_dimensionless=True).get(j, 0) for i in target_dims] for j in canon_dim_units])     exprmat = Matrix([dim_dependencies.get(k, 0) for k in canon_dim_units])     res_exponents = camat.solve_least_squares(exprmat, method=None)    try:        res_exponents = camat.solve(exprmat)    except NonInvertibleMatrixError:        return None     return res_exponents


Question: simplify() returns wrong result when applied to a certain trigonometric expression The function from sympy returns a wrong result when applied to the following trigonometric expression: <img src="\cos\left(\frac{\beta}{2}\right) \sin\left(\frac{\beta}{2}\right) \cos(\beta) \cos(\gamma)^2 \sin(\gamma)"The latter gets simplified to: <img src="\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"instead of: <img src="\cos(\gamma)\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"Here is a piece of code that reproduces the issue: Python version: 3.8 SymPy version: 1.6.2 simplify() returns wrong result when applied to a certain trigonometric expression The function from sympy returns a wrong result when applied to the following trigonometric expression: <img src="\cos\left(\frac{\beta}{2}\right) \sin\left(\frac{\beta}{2}\right) \cos(\beta) \cos(\gamma)^2 \sin(\gamma)"The latter gets simplified to: <img src="\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"instead of: <img src="\cos(\gamma)\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"Here is a piece of code that reproduces the issue: Python version: 3.8 SymPy version: 1.6.2

for a in args:             c = args[a]             c.sort()<del>            no = []</del>             while c:                 k = 0                 cc = ci = c[0]


Question: simplify() returns wrong result when applied to a certain trigonometric expression The function from sympy returns a wrong result when applied to the following trigonometric expression: <img src="\cos\left(\frac{\beta}{2}\right) \sin\left(\frac{\beta}{2}\right) \cos(\beta) \cos(\gamma)^2 \sin(\gamma)"The latter gets simplified to: <img src="\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"instead of: <img src="\cos(\gamma)\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"Here is a piece of code that reproduces the issue: Python version: 3.8 SymPy version: 1.6.2 simplify() returns wrong result when applied to a certain trigonometric expression The function from sympy returns a wrong result when applied to the following trigonometric expression: <img src="\cos\left(\frac{\beta}{2}\right) \sin\left(\frac{\beta}{2}\right) \cos(\beta) \cos(\gamma)^2 \sin(\gamma)"The latter gets simplified to: <img src="\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"instead of: <img src="\cos(\gamma)\frac{\cos(2\beta - 2\gamma) - \cos(2\beta %2B 2\gamma)}{16}"Here is a piece of code that reproduces the issue: Python version: 3.8 SymPy version: 1.6.2

c.remove(cc)                     new.append(newarg**take)                 else:                    no.append(c.pop(0))            c[:] = no                    b = cos(c.pop(0)*a)                    other.append(b**coss[b])          if new:             rv = Mul(*(new + other + [


Question: Symbol instances have dict since 1.7? In version 1.6.2 Symbol instances had no attribute This changes in 1.7 where now exists (and returns an empty dict) I may misinterpret this, but given the purpose of , I assume this is a bug, introduced because some parent class accidentally stopped defining .

This also adds support for LaTeX printing in jupyter notebooks.     """ <ins>    # Since this class is used as a mixin we set empty slots. That means that    # instances of any subclasses that use slots will not need to have a    # __dict__.    __slots__ = ()</ins>     # Note, we always use the default ordering (lex) in __str__ and __repr__,     # regardless of the global setting. See issue 5487.     def __str__(self):


Question: inaccurate rendering of pi**(1/E) This claims to be version ; I just merged from the project master, so I hope this is current. I didn't notice this bug among others in LaTeX and str not fooled:

return prettyForm.__mul__(*a)/prettyForm.__mul__(*b)      # A helper function for _print_Pow to print x**(1/n)    def _print_nth_root(self, base, expt):    def _print_nth_root(self, base, root):         bpretty = self._print(base)          # In very simple cases, use a single-char root sign         if (self._settings['use_unicode_sqrt_char'] and self._use_unicode            and expt is S.Half and bpretty.height() == 1            and root == 2 and bpretty.height() == 1             and (bpretty.width() == 1                  or (base.is_Integer and base.is_nonnegative))):             return prettyForm(*bpretty.left('\N{SQUARE ROOT}'))


Question: inaccurate rendering of pi**(1/E) This claims to be version ; I just merged from the project master, so I hope this is current. I didn't notice this bug among others in LaTeX and str not fooled:

# Construct root sign, start with the \/ shape         _zZ = xobj('/', 1)         rootsign = xobj('\\', 1) + _zZ        # Make exponent number to put above it        if isinstance(expt, Rational):            exp = str(expt.q)            if exp == '2':                exp = ''        else:            exp = str(expt.args[0])        exp = exp.ljust(2)        # Constructing the number to put on root        rpretty = self._print(root)        # roots look bad if they are not a single line        if rpretty.height() != 1:            return self._print(base)**self._print(1/root)        # If power is half, no number should appear on top of root sign        exp = '' if root == 2 else str(rpretty).ljust(2)         if len(exp) > 2:             rootsign = ' '*(len(exp) - 2) + rootsign         # Stack the exponent


Question: inaccurate rendering of pi**(1/E) This claims to be version ; I just merged from the project master, so I hope this is current. I didn't notice this bug among others in LaTeX and str not fooled:

if e is S.NegativeOne:                 return prettyForm("1")/self._print(b)             n, d = fraction(e)            if n is S.One and d.is_Atom and not e.is_Integer and self._settings['root_notation']:                return self._print_nth_root(b, e)            if n is S.One and d.is_Atom and not e.is_Integer and (e.is_Rational or d.is_Symbol) \                    and self._settings['root_notation']:                return self._print_nth_root(b, d)             if e.is_Rational and e < 0:                 return prettyForm("1")/self._print(Pow(b, -e, evaluate=False))


Question: S(0.0) == S.false returns True This issue is related to those listed in . As shown by comparing to returns 2 different results depending on the order in which they are compared: Based on the results of comparison to : I assume we would want to return True as well?

other = _sympify(other)         except SympifyError:             return NotImplemented<del>        if not self:            return not other</del>         if isinstance(other, Boolean):             return False         if other.is_NumberSymbol:


Question: S(0.0) == S.false returns True This issue is related to those listed in . As shown by comparing to returns 2 different results depending on the order in which they are compared: Based on the results of comparison to : I assume we would want to return True as well?

# the mpf tuples             ompf = other._as_mpf_val(self._prec)             return bool(mlib.mpf_eq(self._mpf_, ompf))<ins>        if not self:            return not other</ins>         return False    # Float != non-Number      def __ne__(self, other):


Question: pprint unicode does not format subscripts on Greek letters Good: [ -t₀⋅w₀ -t₁⋅w₀ -t₂⋅w₀] Bad: [ -t₀⋅ω0 -t₁⋅ω0 -t₂⋅ω0]

from collections.abc import Iterable from sympy import Derivative _name_with_digits_p = re.compile(r'^([a-zA-Z]+)([0-9]+)$')_name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)   def split_super_sub(text):


Question: pprint unicode does not format subscripts on Greek letters Good: [ -t₀⋅w₀ -t₁⋅w₀ -t₂⋅w₀] Bad: [ -t₀⋅ω0 -t₁⋅ω0 -t₂⋅ω0]

else:             raise RuntimeError("This should never happen.")     # make a little exception when a name ends with digits, i.e. treat them    # Make a little exception when a name ends with digits, i.e. treat them     # as a subscript too.     m = _name_with_digits_p.match(name)     if m:


Question: does not understand how to simplify complex arguments Just learned about the refine-function, which would come in handy frequently for me. But does not recognize that argument functions simplify for real numbers. I cann't find any open issues identifying this. Easy to fix, though.

return - S.ImaginaryUnit * arg     return _refine_reim(expr, assumptions) <ins>def refine_arg(expr, assumptions):    """    Handler for complex argument    Explanation    ===========    >>> from sympy.assumptions.refine import refine_arg    >>> from sympy import Q, arg    >>> from sympy.abc import x    >>> refine_arg(arg(x), Q.positive(x))    0    >>> refine_arg(arg(x), Q.negative(x))    pi    """    rg = expr.args[0]    if ask(Q.positive(rg), assumptions):        return S.Zero    if ask(Q.negative(rg), assumptions):        return S.Pi    return None</ins>  def _refine_reim(expr, assumptions):     # Helper function for refine_re & refine_im


Question: does not understand how to simplify complex arguments Just learned about the refine-function, which would come in handy frequently for me. But does not recognize that argument functions simplify for real numbers. I cann't find any open issues identifying this. Easy to fix, though.

'atan2': refine_atan2,     're': refine_re,     'im': refine_im,<ins>    'arg': refine_arg,</ins>     'sign': refine_sign,     'MatrixElement': refine_matrixelement }  # type: Dict[str, Callable[[Expr, Boolean], Expr]]


Question: printSingularityFunction() got an unexpected keyword argument 'exp' On a Jupyter Notebook cell, type the following: Then: The following error appears:

tex = r"\left(%s\right)^{%s}" % (tex, exp)         return tex     def _print_SingularityFunction(self, expr):    def _print_SingularityFunction(self, expr, exp=None):         shift = self._print(expr.args[0] - expr.args[1])         power = self._print(expr.args[2])         tex = r"{\left\langle %s \right\rangle}^{%s}" % (shift, power)        if exp is not None:            tex = r"{\left({\langle %s \rangle}^{%s}\right)}^{%s}" % (shift, power, exp)         return tex      def _print_Heaviside(self, expr, exp=None):


Question: Results diverge when use on a matrix or its elemetns create a one-element matrix A as below: when use on matrix A: when use on the single element of A: but if use method on A, the result is the same as above: is this a bug or supposed behavior of matrix calculus?

from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix     parts = [[convert_array_to_matrix(j).doit() for j in i] for i in parts]    parts = [[convert_array_to_matrix(j) for j in i] for i in parts]      def _get_shape(elem):         if isinstance(elem, MatrixExpr):


Question: Results diverge when use on a matrix or its elemetns create a one-element matrix A as below: when use on matrix A: when use on the single element of A: but if use method on A, the result is the same as above: is this a bug or supposed behavior of matrix calculus?

data = [self._build(i) for i in self._lines]         if self.higher != 1:             data += [self._build(self.higher)]        data = [i.doit() for i in data]        data = [i for i in data]         return data      def matrix_form(self):


Question: Improve asrelational for Range Ranges don't have a rule in that file but they are complicated unless their steps are both the same and the modulus of the starting values relative to the step is the same. Note that the following is wrong (but is outside the scope of this PR): It should be Originally posted by in

from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.logic import fuzzy_not, fuzzy_or, fuzzy_andfrom sympy.core.numbers import oo, Integerfrom sympy.core.numbers import oo from sympy.core.relational import Eq from sympy.core.singleton import Singleton, S from sympy.core.symbol import Dummy, symbols, Symbol


Question: Improve asrelational for Range Ranges don't have a rule in that file but they are complicated unless their steps are both the same and the modulus of the starting values relative to the step is the same. Note that the following is wrong (but is outside the scope of this PR): It should be Originally posted by in

if not self:             return S.Zero         dif = self.stop - self.start        if self.has(Symbol):            if dif.has(Symbol) or self.step.has(Symbol) or (                    not self.start.is_integer and not self.stop.is_integer):                raise ValueError('invalid method for symbolic range')        if dif.is_infinite:            return S.Infinity        return Integer(abs(dif//self.step))        n = abs(dif // self.step)        if not n.is_Integer:            if n.is_infinite:                return S.Infinity            raise ValueError('invalid method for symbolic range')        return n      @property     def is_finite_set(self):


Question: Improve asrelational for Range Ranges don't have a rule in that file but they are complicated unless their steps are both the same and the modulus of the starting values relative to the step is the same. Note that the following is wrong (but is outside the scope of this PR): It should be Originally posted by in

def as_relational(self, x):         """Rewrite a Range in terms of equalities and logic operators. """        from sympy.functions.elementary.integers import floor         if self.size == 1:             return Eq(x, self[0])        elif self.size == 0:            return S.false         else:            return And(                Eq(x, floor(x)),                x >= self.inf if self.inf in self else x > self.inf,                x <= self.sup if self.sup in self else x < self.sup)            from sympy.core.mod import Mod            cond = None            if self.start.is_infinite:                if self.stop.is_infinite:                    cond = S.true                else:                    a = self.reversed.start            elif self.start == self.stop:                cond = S.false  # null range            else:                a = self.start            step = abs(self.step)            cond = Eq(Mod(x, step), a % step) if cond is None else cond            return And(cond,                       x >= self.inf if self.inf in self else x > self.inf,                       x <= self.sup if self.sup in self else x < self.sup)  converter[range] = lambda r: Range(r.start, r.stop, r.step)


Question: Doctest failure in See discussion in . CC There was a doctest failure but the test was disabled in to unblock CI. The cause of the failure remains unfixed though. The failure was:

self.latex_vecs = latexs         self.name = name         self._var_dict = {}        #The _dcm_dict dictionary will only store the dcms of parent-child        #relationships. The _dcm_cache dictionary will work as the dcm        #cache.        #The _dcm_dict dictionary will only store the dcms of adjacent parent-child        #relationships. The _dcm_cache dictionary will store calculated dcm along with        #all content of _dcm_dict for faster retrieval of dcms.         self._dcm_dict = {}         self._dcm_cache = {}         self._ang_vel_dict = {}


Question: Doctest failure in See discussion in . CC There was a doctest failure but the test was disabled in to unblock CI. The cause of the failure remains unfixed though. The failure was:

return outdcm      def _dcm(self, parent, parent_orient):        # Reset the _dcm_cache of this frame, and remove it from the        # _dcm_caches of the frames it is linked to. Also remove it from the        # _dcm_dict of its parent        # If parent.oreint(self) is already defined,then        # update the _dcm_dict of parent while over write        # all content of self._dcm_dict and self._dcm_cache        # with new dcm relation.        # Else update _dcm_cache and _dcm_dict of both        # self and parent.         frames = self._dcm_cache.keys()         dcm_dict_del = []         dcm_cache_del = []        for frame in frames:            if frame in self._dcm_dict:                dcm_dict_del += [frame]            dcm_cache_del += [frame]        for frame in dcm_dict_del:            del frame._dcm_dict[self]        for frame in dcm_cache_del:            del frame._dcm_cache[self]        if parent in frames:            for frame in frames:                if frame in self._dcm_dict:                    dcm_dict_del += [frame]                dcm_cache_del += [frame]            # Reset the _dcm_cache of this frame, and remove it from the            # _dcm_caches of the frames it is linked to. Also remove it from the            # _dcm_dict of its parent            for frame in dcm_dict_del:                del frame._dcm_dict[self]            for frame in dcm_cache_del:                del frame._dcm_cache[self]        # Reset the _dcm_dict            self._dcm_dict = self._dlist[0] = {}        # Reset the _dcm_cache            self._dcm_cache = {}         # Add the dcm relationship to _dcm_dict        self._dcm_dict = self._dlist[0] = {}         self._dcm_dict.update({parent: parent_orient.T})         parent._dcm_dict.update({self: parent_orient})        # Also update the dcm cache after resetting it        self._dcm_cache = {}        # Update the dcm cache         self._dcm_cache.update({parent: parent_orient.T})         parent._dcm_cache.update({self: parent_orient})


Question: Doctest failure in See discussion in . CC There was a doctest failure but the test was disabled in to unblock CI. The cause of the failure remains unfixed though. The failure was:

>>> B1.orient_axis(N, N.z, q1)         >>> B2.orient_axis(B1, N.x, q2)         >>> B.orient_axis(B2, N.y, q3)        >>> B.dcm(N).simplify() # doctest: +SKIP        >>> B.dcm(N).simplify()         Matrix([         [ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2), sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1)],         [-sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2), sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3)],


Question: don't canonicalize imageset based on Float While writing this about how to get something resembling a float-version for range to work, I tried to think about how I would do this in SymPy. Although Floats present their own difficulties, there is canonicalization being done with expressions that makes this even worse: That last result should represent an error. The reason it happens is because is replaced with : So while canonicalization is OK for Rationals, it should not be done to Floats. Working around this issue, here is a version of that might work for SymPy:

from sympy import Set, symbols, exp, log, S, Wild, Dummy, oofrom sympy import Set, symbols, exp, log, S, Wild, Dummy, oo, Float from sympy.core import Expr, Add from sympy.core.function import Lambda, _coeff_isneg, FunctionClass from sympy.logic.boolalg import true


Question: don't canonicalize imageset based on Float While writing this about how to get something resembling a float-version for range to work, I tried to think about how I would do this in SymPy. Although Floats present their own difficulties, there is canonicalization being done with expressions that makes this even worse: That last result should represent an error. The reason it happens is because is replaced with : So while canonicalization is OK for Rationals, it should not be done to Floats. Working around this issue, here is a version of that might work for SymPy:

a = Wild('a', exclude=[n])     b = Wild('b', exclude=[n])     match = expr.match(a*n + b)    if match and match[a]:    if match and match[a] and (            not match[a].atoms(Float) and            not match[b].atoms(Float)):         # canonical shift         a, b = match[a], match[b]         if a in [1, -1]:


Question: Unexpected when using simple for particular expressions I am seeing weird behavior with for particular expressions with hyperbolic sinusoids with piecewise arguments. When applying , I obtain an unexpected . For context, I was umbrella-applying a casting from int to float of all int atoms for a bunch of random expressions before using a tensorflow lambdify to avoid potential tensorflow type errors. You can pretend the expression below has a at the end, but below is the MWE that I could produce. See the expression below, and the conditions in which the exception arises. Sympy version: I am not really sure where the issue is, but I think it has something to do with the order of assumptions in this specific type of expression. Here is what I found- The error only (AFAIK) happens with or in place of , otherwise it succeeds The error goes away if removing the division by The error goes away if removing (but stays for most unary functions, , , etc.) The error only happens with real symbols for and ( does not have to be real) Not too sure how to debug this one.

from sympy.core.mul import Mul         from sympy.core.singleton import S         from sympy.core.exprtools import gcd_terms<ins>        from sympy.polys.polyerrors import PolynomialError</ins>         from sympy.polys.polytools import gcd          def doit(p, q):


Question: Unexpected when using simple for particular expressions I am seeing weird behavior with for particular expressions with hyperbolic sinusoids with piecewise arguments. When applying , I obtain an unexpected . For context, I was umbrella-applying a casting from int to float of all int atoms for a bunch of random expressions before using a tensorflow lambdify to avoid potential tensorflow type errors. You can pretend the expression below has a at the end, but below is the MWE that I could produce. See the expression below, and the conditions in which the exception arises. Sympy version: I am not really sure where the issue is, but I think it has something to do with the order of assumptions in this specific type of expression. Here is what I found- The error only (AFAIK) happens with or in place of , otherwise it succeeds The error goes away if removing the division by The error goes away if removing (but stays for most unary functions, , , etc.) The error only happens with real symbols for and ( does not have to be real) Not too sure how to debug this one.

# XXX other possibilities?          # extract gcd; any further simplification should be done by the user        G = gcd(p, q)        if G != 1:            p, q = [                gcd_terms(i/G, clear=False, fraction=False) for i in (p, q)]        try:            G = gcd(p, q)            if G != 1:                p, q = [gcd_terms(i/G, clear=False, fraction=False)                        for i in (p, q)]        except PolynomialError:  # issue 21373            G = S.One         pwas, qwas = p, q          # simplify terms


Question: powdenest(sqrt(sin(x)2), force=True) does not work Since gives , I would expect to be .

return obj         if not isinstance(arg, Expr):             raise TypeError("Bad argument type for Abs(): %s" % type(arg))<ins></ins>         # handle what we can         arg = signsimp(arg, evaluate=False)         n, d = arg.as_numer_denom()


Question: powdenest(sqrt(sin(x)2), force=True) does not work Since gives , I would expect to be .

if isinstance(arg, exp):             return exp(re(arg.args[0]))         if isinstance(arg, AppliedUndef):<ins>            if arg.is_positive:                return arg            elif arg.is_negative:                return -arg</ins>             return         if arg.is_Add and arg.has(S.Infinity, S.NegativeInfinity):             if any(a.is_infinite for a in arg.as_real_imag()):


Question: powdenest(sqrt(sin(x)2), force=True) does not work Since gives , I would expect to be .

arg_ = sign(c)*arg_         else:             arg_ = arg        if arg_.atoms(AppliedUndef):        if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):             return         x, y = arg_.as_real_imag()         rv = atan2(y, x)diff --git a/sympy/simplify/powsimp.py b/sympy/simplify/powsimp.py-- a/sympy/simplify/powsimp.py++ b/sympy/simplify/powsimp.py


Question: powdenest(sqrt(sin(x)2), force=True) does not work Since gives , I would expect to be .

from sympy.simplify.simplify import posify      if force:        eq, rep = posify(eq)        return powdenest(eq, force=False).xreplace(rep)        def _denest(b, e):            if not isinstance(b, (Pow, exp)):                return b.is_positive, Pow(b, e, evaluate=False)            return _denest(b.base, b.exp*e)        reps = []        for p in eq.atoms(Pow, exp):            if isinstance(p.base, (Pow, exp)):                ok, dp = _denest(*p.args)                if ok is not False:                    reps.append((p, dp))        if reps:            eq = eq.subs(reps)        eq, reps = posify(eq)        return powdenest(eq, force=False, polar=polar).xreplace(reps)      if polar:         eq, rep = polarify(eq)


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

relations : dict, optional         Key is a tuple of two strings, who are the names of the systems where        the coordinates transform from and transform to. Value is a tuple of        transformed coordinates.        the coordinates transform from and transform to.        Value is a tuple of the symbols before transformation and a tuple of        the expressions after transformation.      Examples     ========


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

>>> x, y = symbols('x y', real=True)     >>> r, theta = symbols('r theta', nonnegative=True)     >>> relation_dict = {    ... ('Car2D', 'Pol'): (sqrt(x**2 + y**2), atan2(y, x)),    ... ('Pol', 'Car2D'): (r*cos(theta), r*sin(theta))    ... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],    ... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))]     ... }     >>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict)     >>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

if not isinstance(s2, Str):                 s2 = Str(s2)             key = Tuple(s1, s2)            # Old version used Lambda as a value.             if isinstance(v, Lambda):                v = tuple(v(*symbols))                v = (tuple(v.signature), tuple(v.expr))            else:                v = (tuple(v[0]), tuple(v[1]))             rel_temp[key] = v         relations = Dict(rel_temp)


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

if self == sys:             expr = Matrix(self.symbols)         elif key in self.relations:            expr = Matrix(self.relations[key])            expr = Matrix(self.relations[key][1])         elif key[::-1] in self.relations:             expr = Matrix(self._inverse_transformation(sys, self))         else:


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

return Lambda(signature, expr)      @staticmethod    def _inverse_transformation(sys1, sys2):        # Find the transformation relation from sys2 to sys1        forward_transform_expressions = sys1.transform(sys2)        inv_results = solve(            [t[0] - t[1] for t in zip(sys2.symbols, forward_transform_expressions)],            list(sys1.symbols), dict=True)        if len(inv_results) == 0:            raise NotImplementedError(                "Cannot solve inverse of transformation from {} to {}".format(sys1, sys2))        elif len(inv_results) > 1:            raise ValueError(                "Obtained multiple results for inverse of transformation from {} to {}".format(sys1, sys2)            )    def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name):        ret = solve(            [t[0] - t[1] for t in zip(sym2, exprs)],            list(sym1), dict=True)        if len(ret) == 0:            temp = "Cannot solve inverse relation from {} to {}."            raise NotImplementedError(temp.format(sys1_name, sys2_name))        elif len(ret) > 1:            temp = "Obtained multiple inverse relation from {} to {}."            raise ValueError(temp.format(sys1_name, sys2_name))        return ret[0]         inv_results = inv_results[0]    @classmethod    def _inverse_transformation(cls, sys1, sys2):        # Find the transformation relation from sys2 to sys1        forward = sys1.transform(sys2)        inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward,                                         sys1.name, sys2.name)         signature = tuple(sys1.symbols)         return [inv_results[s] for s in signature]      @classmethod     @cacheit     def _indirect_transformation(cls, sys1, sys2):        # Find the transformation relation between two indirectly connected coordinate systems        # Find the transformation relation between two indirectly connected        # coordinate systems        rel = sys1.relations         path = cls._dijkstra(sys1, sys2)        Lambdas = []        for i in range(len(path) - 1):            s1, s2 = path[i], path[i + 1]            Lambdas.append(s1.transformation(s2))        syms = Lambdas[-1].signature        expr = syms        for l in reversed(Lambdas):            expr = l(*expr)        return Lambda(syms, expr)        transforms = []        for s1, s2 in zip(path, path[1:]):            if (s1, s2) in rel:                transforms.append(rel[(s1, s2)])            else:                sym2, inv_exprs = rel[(s2, s1)]                sym1 = tuple(Dummy() for i in sym2)                ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1)                ret = tuple(ret[s] for s in sym2)                transforms.append((sym1, ret))        syms = sys1.args[2]        exprs = syms        for newsyms, newexprs in transforms:            exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs)        return exprs      @staticmethod     def _dijkstra(sys1, sys2):         # Use Dijkstra algorithm to find the shortest path between two indirectly-connected         # coordinate systems        # return value is the list of the names of the systems.         relations = sys1.relations         graph = {}         for s1, s2 in relations.keys():


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

path_dict[newsys][1] = [i for i in path_dict[sys][1]]                     path_dict[newsys][1].append(sys)         visit(sys1)        visit(sys1.name)          while True:             min_distance = max(path_dict.values(), key=lambda x:x[0])[0]


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

break             visit(newsys)         result = path_dict[sys2][1]        result.append(sys2)        result = path_dict[sys2.name][1]        result.append(sys2.name)         if result == [sys2]:        if result == [sys2.name]:             raise KeyError("Two coordinate systems are not connected.")         return result diff --git a/sympy/diffgeom/rn.py b/sympy/diffgeom/rn.py-- a/sympy/diffgeom/rn.py++ b/sympy/diffgeom/rn.py


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

r, theta = symbols('rho theta', nonnegative=True)  relations_2d = {    ('rectangular', 'polar'): (sqrt(x**2 + y**2), atan2(y, x)),    ('polar', 'rectangular'): (r*cos(theta), r*sin(theta)),    ('rectangular', 'polar'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],    ('polar', 'rectangular'): [(r, theta), (r*cos(theta), r*sin(theta))], }  R2_r = CoordSystem('rectangular', R2_origin, (x, y), relations_2d)  # type: Any


Question: diffgeom.CoordSystem.transform with indirect relation raises KeyError Below code is a minimal example for an indirect transform via a temporary intermediate coordinate system. raises a KeyError. MWE: This raises a KeyError. DEBUGGING:

rho, psi, r, theta, phi = symbols('rho psi r theta phi', nonnegative=True)  relations_3d = {    ('rectangular', 'cylindrical'): (sqrt(x**2 + y**2), atan2(y, x), z),    ('cylindrical', 'rectangular'): (rho*cos(psi), rho*sin(psi), z),    ('rectangular', 'spherical'): (sqrt(x**2 + y**2 + z**2),                                   acos(z/sqrt(x**2 + y**2 + z**2)),                                   atan2(y, x)),    ('spherical', 'rectangular'): (r*sin(theta)*cos(phi),                                   r*sin(theta)*sin(phi),                                   r*cos(theta)),    ('cylindrical', 'spherical'): (sqrt(rho**2 + z**2),                                   acos(z/sqrt(rho**2 + z**2)),                                   psi),    ('spherical', 'cylindrical'): (r*sin(theta), phi, r*cos(theta)),    ('rectangular', 'cylindrical'): [(x, y, z),                                     (sqrt(x**2 + y**2), atan2(y, x), z)],    ('cylindrical', 'rectangular'): [(rho, psi, z),                                     (rho*cos(psi), rho*sin(psi), z)],    ('rectangular', 'spherical'): [(x, y, z),                                   (sqrt(x**2 + y**2 + z**2),                                    acos(z/sqrt(x**2 + y**2 + z**2)),                                    atan2(y, x))],    ('spherical', 'rectangular'): [(r, theta, phi),                                   (r*sin(theta)*cos(phi),                                    r*sin(theta)*sin(phi),                                    r*cos(theta))],    ('cylindrical', 'spherical'): [(rho, psi, z),                                   (sqrt(rho**2 + z**2),                                    acos(z/sqrt(rho**2 + z**2)),                                    psi)],    ('spherical', 'cylindrical'): [(r, theta, phi),                                   (r*sin(theta), phi, r*cos(theta))], }  R3_r = CoordSystem('rectangular', R3_origin, (x, y, z), relations_3d)  # type: Any


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

float_numbers.append(x)                     if y.is_Float:                         float_numbers.append(y)            if is_algebraic(coeff):            elif is_algebraic(coeff):                 if floats:                     # there are both algebraics and reals -> EX                     return Falsediff --git a/sympy/polys/matrices/ddm.py b/sympy/polys/matrices/ddm.py-- a/sympy/polys/matrices/ddm.py++ b/sympy/polys/matrices/ddm.py


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

def rref(a):         """Reduced-row echelon form of a and list of pivots"""         b = a.copy()        pivots = ddm_irref(b)        K = a.domain        partial_pivot = K.is_RealField or K.is_ComplexField        pivots = ddm_irref(b, _partial_pivot=partial_pivot)         return b, pivots      def nullspace(a):diff --git a/sympy/polys/matrices/dense.py b/sympy/polys/matrices/dense.py-- a/sympy/polys/matrices/dense.py++ b/sympy/polys/matrices/dense.py


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

ai[j] = sum(map(mul, bi, cTj), ai[j])  def ddm_irref(a):def ddm_irref(a, _partial_pivot=False):     """a  <--  rref(a)"""     # a is (m x n)     m = len(a)


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

pivots = []      for j in range(n):        # Proper pivoting should be used for all domains for performance        # reasons but it is only strictly needed for RR and CC (and possibly        # other domains like RR(x)). This path is used by DDM.rref() if the        # domain is RR or CC. It uses partial (row) pivoting based on the        # absolute value of the pivot candidates.        if _partial_pivot:            ip = max(range(i, m), key=lambda ip: abs(a[ip][j]))            a[i], a[ip] = a[ip], a[i]         # pivot         aij = a[i][j] diff --git a/sympy/polys/matrices/linsolve.py b/sympy/polys/matrices/linsolve.py-- a/sympy/polys/matrices/linsolve.py++ b/sympy/polys/matrices/linsolve.py


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

Aaug = sympy_dict_to_dm(eqsdict, rhs, syms)     K = Aaug.domain     # sdm_irref has issues with float matrices. This uses the ddm_rref()    # function. When sdm_rref() can handle float matrices reasonably this    # should be removed...    if K.is_RealField or K.is_ComplexField:        Aaug = Aaug.to_ddm().rref()[0].to_sdm()     # Compute reduced-row echelon form (RREF)     Arref, pivots, nzcols = sdm_irref(Aaug) diff --git a/sympy/polys/matrices/sdm.py b/sympy/polys/matrices/sdm.py-- a/sympy/polys/matrices/sdm.py++ b/sympy/polys/matrices/sdm.py


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

Ajnz = set(Aj)             for k in Ajnz - Ainz:                 Ai[k] = - Aij * Aj[k]<ins>            Ai.pop(j)            Ainz.remove(j)</ins>             for k in Ajnz & Ainz:                 Aik = Ai[k] - Aij * Aj[k]                 if Aik:


Question: linsolve fails simple system of two equations Any thoughts on why these don't all return the same solution? Thanks!

for l in Ainz - Aknz:                 Ak[l] = - Akj * Ai[l]                 nonzero_columns[l].add(k)<ins>            Ak.pop(j)            Aknz.remove(j)</ins>             for l in Ainz & Aknz:                 Akl = Ak[l] - Akj * Ai[l]                 if Akl:


Question: for , Although we have fixed , it should be extended further for . The behavior for was to expand it in denominator with , so it could be taken as a reference.

from sympy.core.logic import fuzzy_or, fuzzy_and <del></del> def _rewrite_hyperbolics_as_exp(expr):     expr = sympify(expr)     return expr.xreplace({h: h.rewrite(exp)


Question: for , Although we have fixed , it should be extended further for . The behavior for was to expand it in denominator with , so it could be taken as a reference.

else:             return self.func(arg) <ins>    def _eval_expand_trig(self, **hints):        arg = self.args[0]        if arg.is_Add:            from sympy import symmetric_poly            CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args]            p = [[], []]            n = len(arg.args)            for i in range(n, -1, -1):                p[(n - i) % 2].append(symmetric_poly(i, CX))            return Add(*p[0])/Add(*p[1])        elif arg.is_Mul:            from sympy import binomial            coeff, x = arg.as_coeff_Mul(rational=True)            if coeff.is_Integer and coeff > 1:                c = coth(x, evaluate=False)                p = [[], []]                for i in range(coeff, -1, -1):                    p[(coeff - i) % 2].append(binomial(coeff, i)*c**i)                return Add(*p[0])/Add(*p[1])        return coth(arg)</ins>  class ReciprocalHyperbolicFunction(HyperbolicFunction):     """Base class for reciprocal functions of hyperbolic functions. """


Question: for , Although we have fixed , it should be extended further for . The behavior for was to expand it in denominator with , so it could be taken as a reference.

re_part, im_part = self.as_real_imag(deep=True, **hints)         return re_part + S.ImaginaryUnit*im_part <ins>    def _eval_expand_trig(self, **hints):        return self._calculate_reciprocal("_eval_expand_trig", **hints)</ins>     def _eval_as_leading_term(self, x, cdir=0):         return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

while ns:     _k, _ = ns.popitem()     if _k in _greek:        _clash2[_k] = Symbol(_k)        _clash2[_k] = None         _greek.remove(_k)     elif _k in _latin:        _clash1[_k] = Symbol(_k)        _clash1[_k] = None         _latin.remove(_k) _clash = {} _clash.update(_clash1)diff --git a/sympy/core/assumptions.py b/sympy/core/assumptions.py-- a/sympy/core/assumptions.py++ b/sympy/core/assumptions.py


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

>>> check_assumptions(2*x + 1, x)     True <ins>    To see if a number matches the assumptions of an expression, pass    the number as the first argument, else its specific assumptions    may not have a non-None value in the expression:    >>> check_assumptions(x, 3)    >>> check_assumptions(3, x)    True</ins>     ``None`` is returned if ``check_assumptions()`` could not conclude.      >>> check_assumptions(2*x - 1, x)


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

"""     expr = sympify(expr)    if against:        if against is not None and assume:    if against is not None:        if assume:             raise ValueError(                 'Expecting `against` or `assume`, not both.')         assume = assumptions(against)diff --git a/sympy/core/sympify.py b/sympy/core/sympify.py-- a/sympy/core/sympify.py++ b/sympy/core/sympify.py


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

names that are defined in abc).      >>> from sympy.abc import _clash1    >>> _clash1    {'E': E, 'I': I, 'N': N, 'O': O, 'Q': Q, 'S': S}    >>> set(_clash1)    {'E', 'I', 'N', 'O', 'Q', 'S'}     >>> sympify('I & Q', _clash1)     I & Q diff --git a/sympy/parsing/sympy_parser.py b/sympy/parsing/sympy_parser.py-- a/sympy/parsing/sympy_parser.py++ b/sympy/parsing/sympy_parser.py


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

from sympy.core.compatibility import iterable from sympy.core.basic import Basic from sympy.core import Symbolfrom sympy.core.function import arityfrom sympy.core.function import arity, Function from sympy.utilities.misc import filldedent, func_name


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

name = tokVal              if (name in ['True', 'False', 'None']                or iskeyword(name)                # Don't convert attribute access                or (prevTok[0] == OP and prevTok[1] == '.')                # Don't convert keyword arguments                or (prevTok[0] == OP and prevTok[1] in ('(', ',')                    and nextTokNum == OP and nextTokVal == '=')):                    or iskeyword(name)                    # Don't convert attribute access                    or (prevTok[0] == OP and prevTok[1] == '.')                    # Don't convert keyword arguments                    or (prevTok[0] == OP and prevTok[1] in ('(', ',')                        and nextTokNum == OP and nextTokVal == '=')                    # the name has already been defined                    or name in local_dict and local_dict[name] is not None):                 result.append((NAME, name))                 continue             elif name in local_dict:                if isinstance(local_dict[name], Symbol) and nextTokVal == '(':                    result.extend([(NAME, 'Function'),                                   (OP, '('),                                   (NAME, repr(str(local_dict[name]))),                                   (OP, ')')])                local_dict.setdefault(None, set()).add(name)                if nextTokVal == '(':                    local_dict[name] = Function(name)                 else:                    result.append((NAME, name))                    local_dict[name] = Symbol(name)                result.append((NAME, name))                 continue             elif name in global_dict:                 obj = global_dict[name]


Question: parseexpr with localdict I have 2 expressions that differ only in E*x` and I want to parse it: Right, but if And Thank you!

code = compile(evaluateFalse(code), '<string>', 'eval')      try:        return eval_expr(code, local_dict, global_dict)        rv = eval_expr(code, local_dict, global_dict)        # restore neutral definitions for names        for i in local_dict.pop(None, ()):            local_dict[i] = None        return rv     except Exception as e:        # restore neutral definitions for names        for i in local_dict.pop(None, ()):            local_dict[i] = None         raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")


Question: bug in is_subset(Reals) Solving issue has given rise to another bug. Now: This output is incorrect. Correct output is:

from sympy.sets.fancysets import (Integers, Naturals, Reals, Range,     ImageSet, Rationals) from sympy.sets.sets import UniversalSet, imageset, ProductSetfrom sympy.simplify.radsimp import numer  @dispatch(ConditionSet, ConditionSet)  # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811


Question: bug in is_subset(Reals) Solving issue has given rise to another bug. Now: This output is incorrect. Correct output is:

from sympy.core.function import expand_complex         from sympy.solvers.solvers import denoms, solve_linear         from sympy.core.relational import Eq<ins>        def _solution_union(exprs, sym):            # return a union of linear solutions to i in expr;            # if i cannot be solved, use a ConditionSet for solution            sols = []            for i in exprs:                x, xis = solve_linear(i, 0, [sym])                if x == sym:                    sols.append(FiniteSet(xis))                else:                    sols.append(ConditionSet(sym, Eq(i, 0)))            return Union(*sols)</ins>         f = self.lamda.expr         n = self.lamda.variables[0]


Question: bug in is_subset(Reals) Solving issue has given rise to another bug. Now: This output is incorrect. Correct output is:

elif ifree != {n}:             return None         else:            # univarite imaginary part in same variable            x, xis = zip(*[solve_linear(i, 0) for i in Mul.make_args(im) if n in i.free_symbols])            if x and all(i == n for i in x):                base_set -= FiniteSet(xis)            else:                base_set -= ConditionSet(n, Eq(im, 0), S.Integers)            # univarite imaginary part in same variable;            # use numer instead of as_numer_denom to keep            # this as fast as possible while still handling            # simple cases            base_set &= _solution_union(                Mul.make_args(numer(im)), n)         # exclude values that make denominators 0        for i in denoms(f):            if i.has(n):                sol = list(zip(*[solve_linear(i, 0) for i in Mul.make_args(im) if n in i.free_symbols]))                if sol != []:                    x, xis = sol                    if x and all(i == n for i in x):                        base_set -= FiniteSet(xis)                else:                    base_set -= ConditionSet(n, Eq(i, 0), S.Integers)        base_set -= _solution_union(denoms(f), n)         return imageset(lam, base_set)      elif isinstance(other, Interval):


Question: Latex parsing of fractions yields wrong expression due to missing brackets Problematic latex expression: is parsed to: . Expected is: . The missing brackets in the denominator result in a wrong expression. 1.8 1.6.2 root python3 Python 3.6.9 (default, Jan 26 2021, 15:33:00) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. from import parselatex parselatex("\frac{\frac{a^3+b}{c}}{\frac{1}{c^2}}") ((a3 + b)/c)/1/(c2)

b.append(apow(item))                 else:                     if (len(item.args[0].args) != 1 and                            isinstance(item.base, Mul)):                            isinstance(item.base, (Mul, Pow))):                         # To avoid situations like #14160                         pow_paren.append(item)                     b.append(item.base)


Question: Wrong Derivative kind attribute I'm playing around with the attribute. The following is correct: This one is wrong:

ret.update(count.free_symbols)         return ret <ins>    @property    def kind(self):        return self.args[0].kind</ins>     def _eval_subs(self, old, new):         # The substitution (old, new) cannot be done inside         # Derivative(expr, vars) for a variety of reasons


Question: Bug: maximum recusion depth error when checking is_zero of cosh expression The following code causes a error when checked if it is zero:

arg2 = -S.ImaginaryUnit * arg             if arg2.is_extended_nonnegative:                 return arg2<ins>        if arg.is_extended_real:            return</ins>         # reject result if all new conjugates are just wrappers around         # an expression that was already in the arg         conj = signsimp(arg.conjugate(), evaluate=False)


Question: Latex repr of CG with power does not render correctly There seem to be Latex rendering problems when a Clebsch-Gordan coefficient () is, for instance, squared: ! <details<summaryCode snippet</summary</detailsI ran this with Sympy v1.7.1 It could be that this is strictly speaking a Jupyter lab/notebook problem, because the that returns is (I think) valid syntax: Still, a simple fix for would be to wrap the in braces: <details<summaryResult in Jupyter</summary! <details<summaryCode snippet</summary</details</detailsRelated issues: and

from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.physics.wigner import clebsch_gordan, wigner_3j, wigner_6j, wigner_9j<ins>from sympy.printing.precedence import PRECEDENCE</ins>  __all__ = [     'CG',


Question: Latex repr of CG with power does not render correctly There seem to be Latex rendering problems when a Clebsch-Gordan coefficient () is, for instance, squared: ! <details<summaryCode snippet</summary</detailsI ran this with Sympy v1.7.1 It could be that this is strictly speaking a Jupyter lab/notebook problem, because the that returns is (I think) valid syntax: Still, a simple fix for would be to wrap the in braces: <details<summaryResult in Jupyter</summary! <details<summaryCode snippet</summary</details</detailsRelated issues: and

coefficients are defined as [1]_:      .. math ::        C^{j_1,m_1}_{j_2,m_2,j_3,m_3} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle        C^{j_3,m_3}_{j_1,m_1,j_2,m_2} = \left\langle j_1,m_1;j_2,m_2 | j_3,m_3\right\rangle      Parameters     ==========     j1, m1, j2, m2, j3, m3 : Number, Symbol        Terms determining the angular momentum of coupled angular momentum        systems.    j1, m1, j2, m2 : Number, Symbol        Angular momenta of states 1 and 2.    j3, m3: Number, Symbol        Total angular momentum of the coupled system.      Examples     ========


Question: Latex repr of CG with power does not render correctly There seem to be Latex rendering problems when a Clebsch-Gordan coefficient () is, for instance, squared: ! <details<summaryCode snippet</summary</detailsI ran this with Sympy v1.7.1 It could be that this is strictly speaking a Jupyter lab/notebook problem, because the that returns is (I think) valid syntax: Still, a simple fix for would be to wrap the in braces: <details<summaryResult in Jupyter</summary! <details<summaryCode snippet</summary</details</detailsRelated issues: and

CG(3/2, 3/2, 1/2, -1/2, 1, 1)         >>> cg.doit()         sqrt(3)/2<ins>        >>> CG(j1=S(1)/2, m1=-S(1)/2, j2=S(1)/2, m2=+S(1)/2, j3=1, m3=0).doit()        sqrt(2)/2    Compare [2]_.</ins>      See Also     ========


Question: Latex repr of CG with power does not render correctly There seem to be Latex rendering problems when a Clebsch-Gordan coefficient () is, for instance, squared: ! <details<summaryCode snippet</summary</detailsI ran this with Sympy v1.7.1 It could be that this is strictly speaking a Jupyter lab/notebook problem, because the that returns is (I think) valid syntax: Still, a simple fix for would be to wrap the in braces: <details<summaryResult in Jupyter</summary! <details<summaryCode snippet</summary</details</detailsRelated issues: and

==========      .. [1] Varshalovich, D A, Quantum Theory of Angular Momentum. 1988.    .. [2] `Clebsch-Gordan Coefficients, Spherical Harmonics, and d Functions        <https://pdg.lbl.gov/2020/reviews/rpp2020-rev-clebsch-gordan-coefs.pdf>`_        in P.A. Zyla *et al.* (Particle Data Group), Prog. Theor. Exp. Phys.        2020, 083C01 (2020).     """    precedence = PRECEDENCE["Pow"] - 1      def doit(self, **hints):         if self.is_symbolic:


Question: Quaternion class has no overridden evalf method class has no overridden method.

from sympy import integrate from sympy import Matrix from sympy import sympify<ins>from sympy.core.evalf import prec_to_dps</ins> from sympy.core.expr import Expr


Question: Quaternion class has no overridden evalf method class has no overridden method.

return Quaternion(a, b, c, d) <ins>    def _eval_evalf(self, prec):        """Returns the floating point approximations (decimal numbers) of the quaternion.        Returns        =======        Quaternion            Floating point approximations of quaternion(self)        Examples        ========        >>> from sympy.algebras.quaternion import Quaternion        >>> from sympy import sqrt        >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4))        >>> q.evalf()        1.00000000000000        + 0.707106781186547*i        + 0.577350269189626*j        + 0.500000000000000*k        """        return Quaternion(*[arg.evalf(n=prec_to_dps(prec)) for arg in self.args])</ins>     def pow_cos_sin(self, p):         """Computes the pth power in the cos-sin form.


Question: itermonomials returns incorrect monomials when using mindegrees argument returns incorrect monomials when using optional argument For example, the following code introduces three symbolic variables and generates monomials with max and min degree of 3: The code returns , when it should also return monomials such as that also have total degree of 3. This behaviour is inconsistent with the documentation that states that The monomials are also missing when is increased above .

for variable in item:                     if variable != 1:                         powers[variable] += 1                if max(powers.values()) >= min_degree:                if sum(powers.values()) >= min_degree:                     monomials_list_comm.append(Mul(*item))             yield from set(monomials_list_comm)         else:


Question: itermonomials returns incorrect monomials when using mindegrees argument returns incorrect monomials when using optional argument For example, the following code introduces three symbolic variables and generates monomials with max and min degree of 3: The code returns , when it should also return monomials such as that also have total degree of 3. This behaviour is inconsistent with the documentation that states that The monomials are also missing when is increased above .

for variable in item:                     if variable != 1:                         powers[variable] += 1                if max(powers.values()) >= min_degree:                if sum(powers.values()) >= min_degree:                     monomials_list_non_comm.append(Mul(*item))             yield from set(monomials_list_non_comm)     else:


Question: LambertW displaying in jupyter lab When using JupyterLab and trying to raise LambertW function to some power (for example multiplying with itself) then it raises error when trying to display it. Same thing happens if I use sp.Pow() method as well. For example sp.Pow(sp.LambertW(2), 2) causes the error as well.

def _print_Object(self, object):         return self._print(Symbol(object.name))     def _print_LambertW(self, expr):    def _print_LambertW(self, expr, exp=None):        arg0 = self._print(expr.args[0])        exp = r"^{%s}" % (exp,) if exp is not None else ""         if len(expr.args) == 1:            return r"W\left(%s\right)" % self._print(expr.args[0])        return r"W_{%s}\left(%s\right)" % \            (self._print(expr.args[1]), self._print(expr.args[0]))            result = r"W%s\left(%s\right)" % (exp, arg0)        else:            arg1 = self._print(expr.args[1])            result = "W{0}_{{{1}}}\\left({2}\\right)".format(exp, arg1, arg0)        return result      def _print_Morphism(self, morphism):         domain = self._print(morphism.domain)


Question: Issues with Latex printing output in second quantization module There are Latex rendering problems within the "secondquant" module, as it does not correctly interpret double superscripts containing the "dagger" command within Jupyter Notebook. Let's see a minimal example So, it doesn't render correctly, and that's because the double superscript . It should be correct by adding curly brackets

return (12, label, h)      def _latex(self, printer):        return "%s^{%s}_{%s}" % (        return "{%s^{%s}_{%s}}" % (             self.symbol,             "".join([ i.name for i in self.args[1]]),             "".join([ i.name for i in self.args[2]])


Question: Issues with Latex printing output in second quantization module There are Latex rendering problems within the "secondquant" module, as it does not correctly interpret double superscripts containing the "dagger" command within Jupyter Notebook. Let's see a minimal example So, it doesn't render correctly, and that's because the double superscript . It should be correct by adding curly brackets

return "CreateBoson(%s)" % self.state      def _latex(self, printer):        return "b^\\dagger_{%s}" % self.state.name        return "{b^\\dagger_{%s}}" % self.state.name  B = AnnihilateBoson Bd = CreateBoson


Question: Issues with Latex printing output in second quantization module There are Latex rendering problems within the "secondquant" module, as it does not correctly interpret double superscripts containing the "dagger" command within Jupyter Notebook. Let's see a minimal example So, it doesn't render correctly, and that's because the double superscript . It should be correct by adding curly brackets

return "CreateFermion(%s)" % self.state      def _latex(self, printer):        return "a^\\dagger_{%s}" % self.state.name        return "{a^\\dagger_{%s}}" % self.state.name  Fd = CreateFermion F = AnnihilateFermion


Question: imageset over Range does not work Simple example: It throws the exception while it tries to check where is the object.

def __iter__(self):         n = self.size  # validate<ins>        if not (n.has(S.Infinity) or n.has(S.NegativeInfinity) or n.is_Integer):            raise TypeError("Cannot iterate over symbolic Range")</ins>         if self.start in [S.NegativeInfinity, S.Infinity]:             raise TypeError("Cannot iterate over Range with infinite start")         elif self.start != self.stop:


Question: imageset over Range does not work Simple example: It throws the exception while it tries to check where is the object.

n = dif/self.step         if n.is_infinite:             return S.Infinity        if not n.is_Integer or not all(i.is_integer for i in self.args):            raise ValueError('invalid method for symbolic range')        return abs(n)        if  n.is_extended_nonnegative and all(i.is_integer for i in self.args):            from sympy.functions.elementary.integers import floor            return abs(floor(n))        raise ValueError('Invalid method for symbolic Range')      @property     def is_finite_set(self):


Question: imageset over Range does not work Simple example: It throws the exception while it tries to check where is the object.

if not (all(i.is_integer or i.is_infinite                     for i in self.args) and ((self.stop - self.start)/                     self.step).is_extended_positive):                raise ValueError('invalid method for symbolic range')                raise ValueError('Invalid method for symbolic Range')             if i == 0:                 if self.start.is_infinite:                     raise ValueError(ooslice)


Question: imageset over Range does not work Simple example: It throws the exception while it tries to check where is the object.

rv = (self.stop if i < 0 else self.start) + i*self.step             if rv.is_infinite:                 raise ValueError(ooslice)            if 0 <= (rv - self.start)/self.step <= n:            val = (rv - self.start)/self.step            rel = fuzzy_or([val.is_infinite,                            fuzzy_and([val.is_nonnegative, (n-val).is_nonnegative])])            if rel:                 return rv            if rel is None:                raise ValueError('Invalid method for symbolic Range')             raise IndexError("Range index out of range")      @propertydiff --git a/sympy/stats/stochastic_process_types.py b/sympy/stats/stochastic_process_types.py-- a/sympy/stats/stochastic_process_types.py++ b/sympy/stats/stochastic_process_types.py


Question: imageset over Range does not work Simple example: It throws the exception while it tries to check where is the object.

# try to convert to tuple         try:             itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))        except ValueError:        except (TypeError, ValueError):             pass      else:


Question: If n is even, n**2/2 should also be even The following: should return , but it returns (of course, this is also an enhancement). That makes me think that perhaps symbolic integers should keep a more complex "assumptions" method, which generalizes "iseven" and "isodd" to instead contain a dictionary of primes that are known to divide that integer, mapping to minimum and maximum known multiplicity. I would like to think about it and post a proposition/plan, but I am not sure what is the correct github way of doing this. Updated evalisodd to handle more complex inputs Changed the function evalisodd to handle integer inputs that have a denominator, such as The example expression x is recognized by SymPy as an integer, but can be decomposed into n,m,and 1/2. My new function evaluates the oddness of each part and uses this to calculate the oddness of the entire integer. Addresses issue

#_eval_is_integer = lambda self: _fuzzy_group(     #    (a.is_integer for a in self.args), quick_exit=True)     def _eval_is_integer(self):<ins>        from sympy import trailing</ins>         is_rational = self._eval_is_rational()         if is_rational is False:             return False


Question: If n is even, n**2/2 should also be even The following: should return , but it returns (of course, this is also an enhancement). That makes me think that perhaps symbolic integers should keep a more complex "assumptions" method, which generalizes "iseven" and "isodd" to instead contain a dictionary of primes that are known to divide that integer, mapping to minimum and maximum known multiplicity. I would like to think about it and post a proposition/plan, but I am not sure what is the correct github way of doing this. Updated evalisodd to handle more complex inputs Changed the function evalisodd to handle integer inputs that have a denominator, such as The example expression x is recognized by SymPy as an integer, but can be decomposed into n,m,and 1/2. My new function evaluates the oddness of each part and uses this to calculate the oddness of the entire integer. Addresses issue

denominators = []         for a in self.args:             if a.is_integer:                numerators.append(a)                if abs(a) is not S.One:                    numerators.append(a)             elif a.is_Rational:                 n, d = a.as_numer_denom()                numerators.append(n)                denominators.append(d)                if abs(n) is not S.One:                    numerators.append(n)                if d is not S.One:                    denominators.append(d)             elif a.is_Pow:                 b, e = a.as_base_exp()                 if not b.is_integer or not e.is_integer: return