Question: identity = GenericIdentity()     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         check = kwargs.get('check', True)          if not args:


Question: args = list(map(sympify, args))         obj = Basic.__new__(cls, *args)         factor, matrices = obj.as_coeff_matrices()         if check:             validate(*matrices)         if not matrices:             # Should it be             #             # return Basic.__neq__(cls, factor, GenericIdentity()) ?             return factor        if evaluate:            return canonicalize(obj)         return obj      @propertydiff --git a/sympy/matrices/expressions/matpow.py b/sympy/matrices/expressions/matpow.py-- a/sympy/matrices/expressions/matpow.py++ b/sympy/matrices/expressions/matpow.py

Introduce 'evaluate' keyword argument in MatAdd and MatMul . Here is an example: I believe it would be better to add option which canonicallizes the object, so that


Question: class MatPow(MatrixExpr):     def __new__(cls, base, exp):    def __new__(cls, base, exp, evaluate=False, **options):         base = _sympify(base)         if not base.is_Matrix:             raise TypeError("Function parameter should be a matrix")         exp = _sympify(exp)        return super(MatPow, cls).__new__(cls, base, exp)        obj = super(MatPow, cls).__new__(cls, base, exp)        if evaluate:            obj = obj.doit(deep=False)        return obj      @property     def base(self):


Question: ========     sympy.functions.combinatorial.factorials.subfactorial     """    p = multiset_permutations(perm)    indices = range(len(perm))    p0 = next(p)    for pi in p:        if all(pi[i] != p0[i] for i in indices):            yield pi    for p in multiset_permutations(perm):        if not any(i == j for i, j in zip(perm, p)):            yield p   def necklaces(n, k, free=False):

generate_derangements mishandles unsorted perm The following is incorrect: The routine is assuming that the is sorted (though this is not a requirement):


Question: def uniq(seq, result=None):     """     Yield unique elements from ``seq`` as an iterator. The second    parameter ``result``  is used internally; it is not necessary to pass    anything for this.    parameter ``result``  is used internally; it is not necessary    to pass anything for this.    Note: changing the sequence during iteration will raise a    RuntimeError if the size of the sequence is known; if you pass    an iterator and advance the iterator you will change the    output of this routine but there will be no warning.      Examples     ========

uniq modifies list argument When you iterate over a dictionary or set and try to modify it while doing so you get an error from Python: It would be good to do the same thing from within because the output will silently be wrong if you modify a passed list: I think this would entail recording the size at the start and then checking the size and raising a similar RuntimeError if the size changes.


Question: >>> list(uniq([[1], [2, 1], [1]]))     [[1], [2, 1]]     """    try:        n = len(seq)    except TypeError:        n = None    def check():        # check that size of seq did not change during iteration;        # if n == None the object won't support size changing, e.g.        # an iterator can't be changed        if n is not None and len(seq) != n:            raise RuntimeError('sequence changed size during iteration')     try:         seen = set()         result = result or []         for i, s in enumerate(seq):             if not (s in seen or seen.add(s)):                 yield s                check()     except TypeError:         if s not in result:             yield s            check()             result.append(s)         if hasattr(seq, '__getitem__'):             for s in uniq(seq[i + 1:], result):


Question: self._module_format("scipy.special.fresnel"),                 self._print(expr.args[0])) <ins>    def _print_airyai(self, expr):        return "{0}({1})[0]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airyaiprime(self, expr):        return "{0}({1})[1]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airybi(self, expr):        return "{0}({1})[2]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))    def _print_airybiprime(self, expr):        return "{0}({1})[3]".format(                self._module_format("scipy.special.airy"),                self._print(expr.args[0]))</ins>  for k in SciPyPrinter._kf:     setattr(SciPyPrinter, '_print_%s' % k, _print_known_func)

Add more SciPy functions to code printer Here is a list of special functions supported in SciPy: Many of them are not supported in the SciPyPrinter and should be .


Question: return [start + (stop - start) * x / (num-1) for x in range(num)]  def textplot_str(expr, a, b, W=55, H=18):def textplot_str(expr, a, b, W=55, H=21):     """Generator for the lines of the plot"""     free = expr.free_symbols     if len(free) > 1:

Incorrect plot with constants I have attached the screenshot of the plot. The x-axis gets moved to y=3, instead of creating a horizontal line at y=3. !


Question: mi, ma = -1, 1     else:         mi, ma = -1, 1<ins>    y_range = ma - mi    precision = math.floor(math.log(y_range, 10)) - 1    precision *= -1    mi = round(mi, precision)    ma = round(ma, precision)</ins>     y = rescale(y, W, H, mi, ma)      y_bins = linspace(mi, ma, H)


Question: else:                     s[i] = '.' <ins>        if h == 0:            for i in range(W):                s[i] = '_'</ins>         # Print y values         if h in (0, H//2, H - 1):             prefix = ("%g" % y_bins[h]).rjust(margin)[:margin]


Question: s = "".join(s)         if h == H//2:             s = s.replace(" ", "-")        yield prefix + " | " + s        yield prefix + " |" + s      # Print x values    bottom = " " * (margin + 3)    bottom = " " * (margin + 2)     bottom += ("%g" % x[0]).ljust(W//2)     if W % 2 == 1:         bottom += ("%g" % x[W//2]).ljust(W//2)


Question: yield bottom  def textplot(expr, a, b, W=55, H=18):def textplot(expr, a, b, W=55, H=21):     r"""     Print a crude ASCII art plot of the SymPy expression 'expr' (which     should contain a single symbol, e.g. x or something else) over the


Question: >>> from sympy.plotting import textplot     >>> t = Symbol('t')     >>> textplot(sin(t)*t, 0, 15)    14.1605 |                                                   ...            |                                                      .            |                                                  .            |                                                 .     .            |                             ..            |                            /  ..               .            |                           /     .            |                          /    2.30284 | ------...---------------/--------.------------.--------            |   ....   ...           /            | ..          \         /           .          .            |              ..      /             .            |                ..   /                       .            |                  ...                .            |                                            .            |                                      .            |                                       \   .    -11.037 |                                        ...            0                          7.5                        15     14 |                                                  ...        |                                                     .        |                                                 .        |                                                      .        |                                                .        |                            ...        |                           /   .               .        |                          /        |                         /      .        |                        .        .            .    1.5 |----.......--------------------------------------------        |....       \           .          .        |            \         /                      .        |             ..      /             .        |               \    /                       .        |                ....        |                                    .        |                                     .     .        |        |                                      .   .    -11 |_______________________________________________________         0                          7.5                        15     """     for line in textplot_str(expr, a, b, W, H):         print(line)


Question: from sympy.utilities.iterables import multiset, is_palindromic as _palindromic  def digits(n, b=10):def digits(n, b=10, digits=None):     """     Return a list of the digits of ``n`` in base ``b``. The first     element in the list is ``b`` (or ``-b`` if ``n`` is negative).

give a argument Like , I think a argument could be to so the length would be padded with 0s if necessary to reach the given bit length: Tests, too, should be .


Question: >>> from sympy.ntheory.digits import digits     >>> digits(35)     [10, 3, 5]    >>> digits(27, 2)    If the number is negative, the negative sign will be placed on the    base (which is the first element in the returned list):    >>> digits(-35)    [-10, 3, 5]    Bases other than 10 (and greater than 1) can be selected with ``b``:    >>> digits(27, b=2)     [2, 1, 1, 0, 1, 1]    >>> digits(65536, 256)    [256, 1, 0, 0]    >>> digits(-3958, 27)    [-27, 5, 11, 16]    Use the ``digits`` keyword if a certain number of digits is desired:    >>> digits(35, digits=4)    [10, 0, 0, 3, 5]    Parameters    ==========    n: integer        The number whose digits are returned.    b: integer        The base in which digits are computed.    digits: integer (or None for all digits)        The number of digits to be returned (padded with zeros, if        necessary).     """      b = as_int(b)     n = as_int(n)    if b <= 1:        raise ValueError("b must be >= 2")    if b < 2:        raise ValueError("b must be greater than 1")     else:         x, y = abs(n), []         while x >= b:


Question: y.append(x)         y.append(-b if n < 0 else b)         y.reverse()<ins>        ndig = len(y) - 1        if digits is not None:            if ndig > digits:                raise ValueError(                    "For %s, at least %s digits are needed." % (n, ndig))            elif ndig < digits:                y[1:1] = [0]*(digits - ndig)</ins>         return y


Question: from sympy.utilities import sift from sympy.utilities.misc import filldedent from sympy.matrices.expressions.matexpr import MatrixExpr, ZeroMatrix, Identityfrom sympy.matrices.expressions.matexpr import MatrixExpr, ZeroMatrix, Identity, MatrixElement from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matpow import MatPow

Wrong matrix element fetched from BlockMatrix Given this code: I get this output: is the wrong here. should not be simplified as that element may come from either or .


Question: def _entry(self, i, j, **kwargs):         # Find row entry        orig_i, orig_j = i, j         for row_block, numrows in enumerate(self.rowblocksizes):            if (i < numrows) != False:            cmp = i < numrows            if cmp == True:                 break            else:            elif cmp == False:                 i -= numrows            elif row_block < self.blockshape[0] - 1:                # Can't tell which block and it's not the last one, return unevaluated                return MatrixElement(self, orig_i, orig_j)         for col_block, numcols in enumerate(self.colblocksizes):            if (j < numcols) != False:            cmp = j < numcols            if cmp == True:                 break            else:            elif cmp == False:                 j -= numcols            elif col_block < self.blockshape[1] - 1:                return MatrixElement(self, orig_i, orig_j)         return self.blocks[row_block, col_block][i, j]      @property


Question: return S.Infinity         return Integer(abs(dif//self.step)) <ins>    @property    def is_finite_set(self):        if self.start.is_integer and self.stop.is_integer:            return True        return self.size.is_finite</ins>     def __nonzero__(self):         return self.start != self.stop

isfiniteset property not implemented for Range Currently, returns nothing, since isfiniteset is not implemented in class Range. I'd like to do that. I was thinking of something like this: Any suggestions/views/ideas are highly appreciated. I will submit a PR for the above changes soon. Also there are some other issues, like: and don't work for ranges in which one of the elements is a symbolic integer, i.e., Any ideas regarding fixing the same are highly appreciated, I'd really like to fix it.


Question: return lc, []      f, F = dmp_sqf_part(f, u, K), f    s, g, r = dmp_sqf_norm(f, u, K)    s, g, r = dmp_sqf_norm(F, u, K)      factors = dmp_factor_list_include(r, u, K.dom)

Factor with extension=True drops a factor of y-1 I guess this related (or a duplicate of?) This is from stackoverflow: Factor with extension=True drops a factor of y-1 <!-- Your title above should be a short description of what was changed. Do not include the issue number in the title. --Factor with extension=True drops a factor of y-1 <!-- 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 --NO ENTRY <!-- END RELEASE NOTES --


Question: return recursor(self, ())      @staticmethod    def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):    def _contract_and_permute_with_metric(metric, array, pos, dim):        # TODO: add possibility of metric after (spinors)         from .array import tensorcontraction, tensorproduct, permutedims         array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))        permu = list(range(dim))        permu[0], permu[pos] = permu[pos], permu[0]        return permutedims(array, permu)    @staticmethod    def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict):        from .array import permutedims         index_types1 = [i.tensor_index_type for i in free_ind1]          # Check if variance of indices needs to be fixed:

Tensor contractions are wrong This is essentially a generalization of . The problem in the current implementation is that contractions are handled before applications of the metric, which leads to incorrect results such as in . In : And thus, the issue is that is being called prior to (where the metric is applied). The reason that this ordering matters is because tensor contraction is itself the abstraction of applying the metric to the tensors that represent psuedo-riemannian manifolds. In essence, it means that we must have it that !; however, this isn't the case here. I've tried tampering with the code above, but by the way tensors have been designed, this bug is essentially unavoidable. As a consequence, the tensor module needs to be refactored in order to get accurate results. (Also, I couldn't help but notice that the last argument to isn't used). had mentioned that he had this sort of refactoring in the works, but based on his fork, progress seems to be slow. I think discussions should be in order for reorganizing how tensors actually represent their components in this module.


Question: if len(set(free_ind1) & set(free_ind2)) < len(free_ind1):             raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) <del>        # TODO: add possibility of metric after (spinors)        def contract_and_permute(metric, array, pos):            array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos))            permu = list(range(len(free_ind1)))            permu[0], permu[pos] = permu[pos], permu[0]            return permutedims(array, permu)</del>         # Raise indices:         for pos in pos2up:             index_type_pos = index_types1[pos]  # type: TensorIndexType


Question: raise ValueError("No metric provided to lower index")             metric = replacement_dict[index_type_pos]             metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric)            array = contract_and_permute(metric_inverse, array, pos)            array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1))         # Lower indices:         for pos in pos2down:             index_type_pos = index_types1[pos]  # type: TensorIndexType             if index_type_pos not in replacement_dict:                 raise ValueError("No metric provided to lower index")             metric = replacement_dict[index_type_pos]            array = contract_and_permute(metric, array, pos)            array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1))          if free_ind1:             permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1)


Question: # Remove elements in `dum2` from `dum1`:             dum1 = [pair for pair in dum1 if pair not in dum2]         if len(dum1) > 0:            indices1 = self.get_indices()             indices2 = other.get_indices()             repl = {}             for p1, p2 in dum1:                 repl[indices2[p2]] = -indices2[p1]                for pos in (p1, p2):                    if indices1[pos].is_up ^ indices2[pos].is_up:                        metric = replacement_dict[indices1[pos].tensor_index_type]                        if indices1[pos].is_up:                            metric = _TensorDataLazyEvaluator.inverse_matrix(metric)                        array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2))             other = other.xreplace(repl).doit()             array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2))


Question: def _entry(self, i, j, **kwargs):         return S.Zero <del>    def __nonzero__(self):        return False    __bool__ = __nonzero__</del> class GenericZeroMatrix(ZeroMatrix):     """     A zero matrix without a specified shape

ZeroMatrix should not be falsey We have: I don't see any sense in having a ZeroMatrix instance evaluate to False. This happens because of the method defined for : The method is not needed now that Python 2 is not supported. The method is not needed because a should not evaluate to False in a boolean context. The linked lines of code should simply be removed.


Question: from .singleton import S from .operations import AssocOp from .cache import cacheitfrom .logic import fuzzy_not, _fuzzy_groupfrom .logic import fuzzy_not, _fuzzy_group, fuzzy_and from .compatibility import reduce from .expr import Expr from .parameters import global_parameters

test('') fails on master ? test('') seems to fail on master. I'm running Python3.5, sympy-dev, MacOS 10.15.3


Question: 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         n, d = fraction(self)        if not is_rational:            _self = n/d            if _self != self:                return _self.is_integer        # 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            elif d == S(2):        if d.is_even:            if d.is_prime:  # literal or symbolic 2                 return n.is_even        # if d is even -- 0 or not -- the        # result is not an integer        if n.is_odd and d.is_even:            return False            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)])      def _eval_is_polar(self):         has_polar = any(arg.is_polar for arg in self.args)


Question: >>> X[:, 1:5][5:8, :]     X[5:8, 1:5]     >>> X[1:9:2, 2:6][1:3, 2]    X[3:7:2, 4]    X[3:7:2, 4:5]     """     row = slice_of_slice(parent.rowslice, rowslice)     col = slice_of_slice(parent.colslice, colslice)diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py-- a/sympy/printing/latex.py++ b/sympy/printing/latex.py

Improvement to printing symbolic matrix slices Printing of slices seems sub-optimal, so here are my proposed changes. Let me know if any of this is controversial. Assuming A[:, :] unchanged A[5:, 5:] A[::2, ::2] unchanged A[0, 0] A[0, 0] All of these would affect the str/pretty/latex printer. I see no reason to drop the '0' from the start of a slice, but not 'n' at the end, especially since we otherwise never hint at the dimensions of the matrix while printing. Also, brackets are missing, making slices of composites display in an unfortunate way: (A + B)[:2, :2] A + B[:2, :2]


Question: + '_{%s, %s}' % (self._print(expr.i), self._print(expr.j))      def _print_MatrixSlice(self, expr):        def latexslice(x):        def latexslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return ':'.join(map(self._print, x))        return (self._print(expr.parent) + r'\left[' +                latexslice(expr.rowslice) + ', ' +                latexslice(expr.colslice) + r'\right]')        return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + r'\left[' +                latexslice(expr.rowslice, expr.parent.rows) + ', ' +                latexslice(expr.colslice, expr.parent.cols) + r'\right]')      def _print_BlockMatrix(self, expr):         return self._print(expr.blocks)diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py-- a/sympy/printing/pretty/pretty.py++ b/sympy/printing/pretty/pretty.py


Question: def _print_MatrixSlice(self, m):         # XXX works only for applied functions        from sympy.matrices import MatrixSymbol         prettyFunc = self._print(m.parent)        def ppslice(x):        if not isinstance(m.parent, MatrixSymbol):            prettyFunc = prettyForm(*prettyFunc.parens())        def ppslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return prettyForm(*self._print_seq(x, delimiter=':'))        prettyArgs = self._print_seq((ppslice(m.rowslice),            ppslice(m.colslice)), delimiter=', ').parens(left='[', right=']')[0]        prettyArgs = self._print_seq((ppslice(m.rowslice, m.parent.rows),            ppslice(m.colslice, m.parent.cols)), delimiter=', ').parens(left='[', right=']')[0]          pform = prettyForm(             binding=prettyForm.FUNC, *stringPict.next(prettyFunc, prettyArgs))diff --git a/sympy/printing/str.py b/sympy/printing/str.py-- a/sympy/printing/str.py++ b/sympy/printing/str.py


Question: + '[%s, %s]' % (self._print(expr.i), self._print(expr.j))      def _print_MatrixSlice(self, expr):        def strslice(x):        def strslice(x, dim):             x = list(x)             if x[2] == 1:                 del x[2]            if x[1] == x[0] + 1:                del x[1]             if x[0] == 0:                 x[0] = ''            if x[1] == dim:                x[1] = ''             return ':'.join(map(lambda arg: self._print(arg), x))        return (self._print(expr.parent) + '[' +                strslice(expr.rowslice) + ', ' +                strslice(expr.colslice) + ']')        return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' +                strslice(expr.rowslice, expr.parent.rows) + ', ' +                strslice(expr.colslice, expr.parent.cols) + ']')      def _print_DeferredVector(self, expr):         return expr.name


Question: def dup_zz_mignotte_bound(f, K):    """Mignotte bound for univariate polynomials in `K[x]`. """    a = dup_max_norm(f, K)    b = abs(dup_LC(f, K))    n = dup_degree(f)    """    The Knuth-Cohen variant of Mignotte bound for    univariate polynomials in `K[x]`.     return K.sqrt(K(n + 1))*2**n*a*b    Examples    ========    >>> from sympy.polys import ring, ZZ    >>> R, x = ring("x", ZZ)    >>> f = x**3 + 14*x**2 + 56*x + 64    >>> R.dup_zz_mignotte_bound(f)    152    By checking `factor(f)` we can see that max coeff is 8    Also consider a case that `f` is irreducible for example `f = 2*x**2 + 3*x + 4`    To avoid a bug for these cases, we return the bound plus the max coefficient of `f`    >>> f = 2*x**2 + 3*x + 4    >>> R.dup_zz_mignotte_bound(f)    6    Lastly,To see the difference between the new and the old Mignotte bound    consider the irreducible polynomial::    >>> f = 87*x**7 + 4*x**6 + 80*x**5 + 17*x**4 + 9*x**3 + 12*x**2 + 49*x + 26    >>> R.dup_zz_mignotte_bound(f)    744    The new Mignotte bound is 744 whereas the old one (SymPy 1.5.1) is 1937664.    References    ==========    ..[1] [Abbott2013]_    """    from sympy import binomial    d = dup_degree(f)    delta = _ceil(d / 2)    delta2 = _ceil(delta / 2)    # euclidean-norm    eucl_norm = K.sqrt( sum( [cf**2 for cf in f] ) )    # biggest values of binomial coefficients (p. 538 of reference)    t1 = binomial(delta - 1, delta2)    t2 = binomial(delta - 1, delta2 - 1)    lc = K.abs(dup_LC(f, K))   # leading coefficient    bound = t1 * eucl_norm + t2 * lc   # (p. 538 of reference)    bound += dup_max_norm(f, K) # add max coeff for irreducible polys    bound = _ceil(bound / 2) * 2   # round up to even integer     return bound  def dmp_zz_mignotte_bound(f, u, K):     """Mignotte bound for multivariate polynomials in `K[X]`. """

improvement The method can be significantly improved by using the Knuth-Cohen bound instead. After our research with Prof. Ag.Akritas we have implemented the Knuth-Cohen bound among others, and compare them among dozens of polynomials with different degree, density and coefficients range. Considering the results and the feedback from Mr.Kalevi Suominen, our proposal is that the mignottebound should be replaced by the knuth-cohen bound. Also, for mutli-variants polynomials should be replaced appropriately.


Question: def _print_list(self, expr):         return "[%s]" % self.reprify(expr, ", ") <ins>    def _print_dict(self, expr):        sep = ", "        dict_kvs = ["%s: %s" % (self.doprint(key), self.doprint(value)) for key, value in expr.items()]        return "{%s}" % sep.join(dict_kvs)    def _print_set(self, expr):        if not expr:            return "set()"        return "{%s}" % self.reprify(expr, ", ")</ins>     def _print_MatrixBase(self, expr):         # special case for some empty matrices         if (expr.rows == 0) ^ (expr.cols == 0):

srepr not printing dict and set properly prints the element in and correctly. However, prints the elements in and wrong. Is this behavior intended? If it isn't, fixing it will be an easy job.


Question: if arg.is_extended_real:             return Heaviside(arg, H0=S(1)/2) * 2 - 1 <ins>    def _eval_rewrite_as_Abs(self, arg, **kwargs):        return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))</ins>     def _eval_simplify(self, **kwargs):         return self.func(self.args[0].factor())  # XXX include doit?

Rewrite sign as abs In sympy the function is defined as for all complex non-zero . There should be a way to rewrite the sign in terms of e.g.: I'm not sure how the possibility of being zero should be handled currently we have Maybe should be as well. Otherwise maybe rewrite as Abs would have to be careful about the possibility of the arg being zero (that would make the rewrite fail in most cases).


Question: >>> _.subs(y, 1)     ConditionSet(y, y < 1, FiniteSet(z)) <del>    Notes    =====</del>     If no base set is specified, the universal set is implied:      >>> ConditionSet(x, x < 1).base_set

Strange/wrong? behaviour of subs with ConditionSet / ImageSet I'm not sure what to think of the following: The first two outputs are completely as expected, but if I construct a similar ConditionSet with an ImageSet instead of a FiniteSet, a plain gives a strange result (). It's as if the bound variable of the ConditionSet were mistaken for a . Only after having typed the above, I found issue , so I'd like to add that a subs on the plain ImageSet is working as intended:


Question: Although the name is usually respected, it must be replaced if     the base set is another ConditionSet and the dummy symbol    and appears as a free symbol in the base set and the dummy symbol    appears as a free symbol in the base set and the dummy symbol     of the base set appears as a free symbol in the condition:      >>> ConditionSet(x, x < y, ConditionSet(y, x + y < 2, S.Integers))


Question: >>> _.subs(_.sym, Symbol('_x'))     ConditionSet(_x, (_x < y) & (_x + x < 2), Integers)<ins></ins>     """     def __new__(cls, sym, condition, base_set=S.UniversalSet):         # nonlinsolve uses ConditionSet to return an unsolved system


Question: # the base set should be filtered and if new is not in             # the base set then this substitution is ignored             return self.func(sym, cond, base)        cond = self.condition.subs(old, new)        base = self.base_set.subs(old, new)        if cond is S.true:            return ConditionSet(new, Contains(new, base), base)        return self.func(self.sym, cond, base)        else:            cond = self.condition.subs(old, new)            base = self.base_set.subs(old, new)            # The condition may have become true due to assumptions            # on 'sym'. In order for .subs() to be consistent with            # __new__ we *don't* check if 'sym' actually belongs to            # 'base'. In other words: assumptions are ignored.            return self.func(self.sym, cond, base)      def dummy_eq(self, other, symbol=None):         if not isinstance(other, self.func):


Question: if not isinstance(rv, dict):             return rv.xreplace(urep)         else:            return {urep.get(k, k): v for k, v in rv.items()}            return {urep.get(k, k): v.xreplace(urep) for k, v in rv.items()}      if evaluate is None:         evaluate = global_parameters.evaluate

sympy 1.6.1 ? Hi, is there any plan on releasing 1.6.1, just like we had 1.5.1 shortly after 1.5? , but the patches we've submitted have already been merged into SymPy master, and we're looking forward to jump to 1.6. Thanks!


Question: while kern in s:                 kern += choice(string.ascii_letters + string.digits)             s = s.replace(' ', kern)        hit = kern in s            hit = kern in s        else:            hit = False      for i in range(2):         try:

kernS: 'kern' referenced before assignment from import kernS text = "(2*x)/(x-1)" expr = kernS(text) // hit = kern in s // UnboundLocalError: local variable 'kern' referenced before assignment


Question: if isinstance(element, FracElement):             if self == element.field:                 return element            if isinstance(self.domain, FractionField) and \                self.domain.field == element.field:                return self.ground_new(element)            elif isinstance(self.domain, PolynomialRing) and \                self.domain.ring.to_field() == element.field:                return self.ground_new(element)             else:                 raise NotImplementedError("conversion")         elif isinstance(element, PolyElement):             denom, numer = element.clear_denoms()            numer = numer.set_ring(self.ring)            if isinstance(self.domain, PolynomialRing) and \                numer.ring == self.domain.ring:                numer = self.ring.ground_new(numer)            elif isinstance(self.domain, FractionField) and \                numer.ring == self.domain.field.to_ring():                numer = self.ring.ground_new(numer)            else:                numer = numer.set_ring(self.ring)             denom = self.ring.ground_new(denom)             return self.raw_new(numer, denom)         elif isinstance(element, tuple) and len(element) == 2:

GeneratorsError raised when creating element of fraction field of polynomial ring I see this construction is not possible while it can be constructed from an element of The same error raises for an element of So this can be relevant


Question: """Hermitian conjugation.""" from __future__ import print_function, divisionfrom sympy.core import Exprfrom sympy.core import Expr, Mul from sympy.functions.elementary.complexes import adjoint  __all__ = [

Dagger() * IdentityOperator() is not simplified As discussed on the mailing list the following does not work.


Question: return obj         return Expr.__new__(cls, arg)     def __mul__(self, other):        from sympy.physics.quantum import IdentityOperator        if isinstance(other, IdentityOperator):            return self        return Mul(self, other) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])diff --git a/sympy/physics/quantum/operator.py b/sympy/physics/quantum/operator.py-- a/sympy/physics/quantum/operator.py++ b/sympy/physics/quantum/operator.py


Question: def __mul__(self, other):         if isinstance(other, Operator):        if isinstance(other, (Operator, Dagger)):             return other          return Mul(self, other)


Question: pivots    = list(filter(lambda p: p < col, pivots))     rank      = len(pivots)     # Bring to block form    permutation = Matrix(range(col)).T    # Get index of free symbols (free parameters)    # non-pivots columns are free variables    free_var_index = [c for c in range(A.cols) if c not in pivots]     for i, c in enumerate(pivots):        permutation.col_swap(i, c)    # Bring to block form    permutation = Matrix(pivots + free_var_index).T      # check for existence of solutions     # rank of aug Matrix should be equal to rank of coefficient matrix     if not v[rank:, :].is_zero_matrix:         raise ValueError("Linear system has no solution")     # Get index of free symbols (free parameters)    # non-pivots columns are free variables    free_var_index = permutation[len(pivots):]     # Free parameters     # what are current unnumbered free symbol names?     name = uniquely_named_symbol('tau', aug,

Wrong answer when using "linsolve" to solve a system of linear equations ! I can get the correct answer when I use the function "solve". However, when I use the "linsolve", it returns a wrong answer to me. It is a very serious bug and I hope that your team can fix it. The following part is my code: (I also upload it with the name "".)


Question: col - rank, B_cols)      # Full parametric solution    V        = A[:rank, [c for c in range(A.cols) if c not in pivots]]    V        = A[:rank, free_var_index]     vt       = v[:rank, :]     free_sol = tau.vstack(vt - V * tau, tau)


Question: # 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)

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)


Question: 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):

() 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.


Question: 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``

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.


Question: 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: 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: _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: 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: 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']

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:


Question: _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: 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

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 --


Question: 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: 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: >>> 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: 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: >>> 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: {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     ==========

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.


Question: 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: 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: ]  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

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.


Question: 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: 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: 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: ).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:

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


Question: # 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:

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:


Question: 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

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?


Question: 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: 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

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


Question: 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

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:


Question: 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: for a in args:             c = args[a]             c.sort()<del>            no = []</del>             while c:                 k = 0                 cc = ci = c[0]

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


Question: 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: 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):

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 .


Question: 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}'))

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:


Question: # 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: 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: 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:

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?


Question: # 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: 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):

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


Question: 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: 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

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.


Question: '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: 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):

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


Question: 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):

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?


Question: 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: 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

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


Question: 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: 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: 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 = {}

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:


Question: 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: >>> 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: 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

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:


Question: 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: 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):

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.


Question: # 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: 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()

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


Question: 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: 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: 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: 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     ========

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:


Question: >>> 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: 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: 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: 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: 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: 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: 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: 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: 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

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


Question: 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: 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: 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: 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: 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: 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: 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)

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.


Question: 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: 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: 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

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!


Question: >>> 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: """     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: 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: 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: 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: 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: 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

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


Question: 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: 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):