Question: ImageSet of n**2-1 returns EmptySet as intersection with Integers (diophantine bug)

for z0 in range(0, abs(_c)):                     # Check if the coefficients of y and x obtained are integers or not                     if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and                            divisible(e*sqc**g*z0**2 + E*z0 + e*sqc*F, _c)):                            divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):                         sol.add((solve_x(z0), solve_y(z0)))      # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

ref = self.start         elif self.stop.is_finite:             ref = self.stop        else:            return other.is_Integer        if (ref - other) % self.step:  # off sequence        else:  # both infinite; step is +/- 1 (enforced by __new__)            return S.true        if self.size == 1:            return Eq(other, self[0])        res = (ref - other) % self.step        if res == S.Zero:            return And(other >= self.inf, other <= self.sup)        elif res.is_Integer:  # off sequence             return S.false        return _sympify(other >= self.inf and other <= self.sup)        else:  # symbolic/unsimplified residue modulo step            return None      def __iter__(self):         if self.has(Symbol):


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

def as_relational(self, x):         """Rewrite a Range in terms of equalities and logic operators. """         from sympy.functions.elementary.integers import floor        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)        if self.size == 1:            return Eq(x, self[0])        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)   # Using range from compatibility above (xrange on Py2)diff --git a/sympy/sets/handlers/issubset.py b/sympy/sets/handlers/issubset.py-- a/sympy/sets/handlers/issubset.py++ b/sympy/sets/handlers/issubset.py


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

from sympy import Sfrom sympy import S, Symbol from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or from sympy.core.relational import Eq from sympy.sets.sets import FiniteSet, Interval, Set, Union


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

cond_right = a_range.sup <= b_interval.right         return fuzzy_and([cond_left, cond_right]) @dispatch(Range, FiniteSet)def is_subset_sets(a_range, b_finiteset): # noqa:F811    try:        a_size = a_range.size    except ValueError:        # symbolic Range of unknown size        return None    if a_size > len(b_finiteset):        return False    elif any(arg.has(Symbol) for arg in a_range.args):        return fuzzy_and(b_finiteset.contains(x) for x in a_range)    else:        # Checking A \ B == EmptySet is more efficient than repeated naive        # membership checks on an arbitrary FiniteSet.        a_set = set(a_range)        b_remaining = len(b_finiteset)        # Symbolic expressions and numbers of unknown type (integer or not) are        # all counted as "candidates", i.e. *potentially* matching some a in        # a_range.        cnt_candidate = 0        for b in b_finiteset:            if b.is_Integer:                a_set.discard(b)            elif fuzzy_not(b.is_integer):                pass            else:                cnt_candidate += 1            b_remaining -= 1            if len(a_set) > b_remaining + cnt_candidate:                return False            if len(a_set) == 0:                return True        return None @dispatch(Interval, Range) def is_subset_sets(a_interval, b_range): # noqa:F811     if a_interval.measure.is_extended_nonzero:diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

else:             args = list(map(sympify, args))         args = list(ordered(set(args), Set._infimum_key))        _args_set = set(args)        args = list(ordered(_args_set, Set._infimum_key))         obj = Basic.__new__(cls, *args)        obj._args_set = _args_set         return obj      def _eval_Eq(self, other):


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

"""         Tests whether an element, other, is in the set.         Relies on Python's set class. This tests for object equality        All inputs are sympified        The actual test is for mathematical equality (as opposed to        syntactical equality). In the worst case all elements of the        set must be checked.          Examples         ========


Question: Range(1).intersect(FiniteSet(n)) raises TypeError: cannot determine truth value of Relational

False          """        # evaluate=True is needed to override evaluate=False context;        # we need Eq to do the evaluation        return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True)) for e in self.args)        if other in self._args_set:            return True        else:            # evaluate=True is needed to override evaluate=False context;            # we need Eq to do the evaluation            return fuzzy_or(fuzzy_bool(Eq(e, other, evaluate=True))                for e in self.args)      def _eval_is_subset(self, other):         return fuzzy_and(other._contains(e) for e in self.args)


Question: Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ? Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ?

@property     def _boundary(self):        return self        return S.Reals   class Naturals(with_metaclass(Singleton, Set)):diff --git a/sympy/sets/handlers/union.py b/sympy/sets/handlers/union.py-- a/sympy/sets/handlers/union.py++ b/sympy/sets/handlers/union.py


Question: Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ? Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ?

from sympy import (Interval, Intersection, Set, EmptySet, S, sympify,                    FiniteSet, Union, ComplexRegion, ProductSet) from sympy.multipledispatch import dispatchfrom sympy.sets.fancysets import Integersfrom sympy.sets.fancysets import (Naturals, Naturals0, Integers, Rationals,                                  Reals) from sympy.sets.sets import UniversalSet  @dispatch(Naturals0, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Rationals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Naturals0)def union_sets(a, b): # noqa:F811    return a@dispatch(Reals, Rationals)def union_sets(a, b): # noqa:F811    return a @dispatch(Integers, Set) def union_sets(a, b): # noqa:F811     intersect = Intersection(a, b)diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ? Are of 's properties valid? currently, there properties aren't initialized . if there properties are thought wheather Q(S.Rationals) is open or closed set in R (S.Reals), should return and . if use there properties as undefined, should return a exception ?

def is_open(self):         """         Property method to check whether a set is open.         A set is open if and only if it has an empty intersection with its        boundary.        boundary. In particular, a subset A of the reals is open if and only        if each one of its points is contained in an open interval that is a        subset of A.          Examples         ========         >>> from sympy import S         >>> S.Reals.is_open         True        >>> S.Rationals.is_open        False         """        if not Intersection(self, self.boundary):            return True        # We can't confidently claim that an intersection exists        return None        return Intersection(self, self.boundary).is_empty      @property     def is_closed(self):         """        A property method to check whether a set is closed. A set is closed        if its complement is an open set.        A property method to check whether a set is closed.        A set is closed if its complement is an open set. The closedness of a        subset of the reals is determined with respect to R and its standard        topology.          Examples         ========


Question: diophantine: incomplete results depending on syms order with permute=True diophantine: incomplete results depending on syms order with permute=True

if syms != var:                 dict_sym_index = dict(zip(syms, range(len(syms))))                 return {tuple([t[dict_sym_index[i]] for i in var])                            for t in diophantine(eq, param)}                            for t in diophantine(eq, param, permute=permute)}         n, d = eq.as_numer_denom()         if n.is_number:             return set()


Question: Recursion error: sqrt(1 / tan(1 + I)) There should be an additional check on this line:

if _half(other):                         if b.is_negative is True:                             return S.NegativeOne**other*Pow(-b, e*other)                        if b.is_extended_real is False:                            return Pow(b.conjugate()/Abs(b)**2, other)                        elif b.is_negative is False:                            return Pow(b, -other)                 elif e.is_even:                     if b.is_extended_real:                         b = abs(b)


Question: nthrootmod function misses one root of x = 0 mod p. When in the equation x*n = a mod p , when a % p == 0. Then x = 0 mod p is also a root of this equation. But right now does not check for this condition. has a root . But it does not return it.

from sympy.core.compatibility import as_int, range from sympy.core.function import Function<ins>from sympy.utilities.iterables import cartes</ins> from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S


Question: nthrootmod function misses one root of x = 0 mod p. When in the equation x*n = a mod p , when a % p == 0. Then x = 0 mod p is also a root of this equation. But right now does not check for this condition. has a root . But it does not return it.

return res     return min(res) <ins>def _nthroot_mod_composite(a, n, m):    """    Find the solutions to ``x**n = a mod m`` when m is not prime.    """    from sympy.ntheory.modular import crt    f = factorint(m)    dd = {}    for p, e in f.items():        tot_roots = set()        if e == 1:            tot_roots.update(nthroot_mod(a, n, p, True) or [])        else:            for root in nthroot_mod(a, n, p, True) or []:                rootn = pow(root, n)                diff = (rootn // (root or 1) * n) % p                if diff != 0:                    ppow = p                    for j in range(1, e):                        ppow *= p                        root = (root - (rootn - a) * mod_inverse(diff, p)) % ppow                    tot_roots.add(root)                else:                    new_base = p                    roots_in_base = {root}                    while new_base < pow(p, e):                        new_base *= p                        new_roots = set()                        for k in roots_in_base:                            if (pow(k, n) - a) % (new_base) != 0:                                continue                            while k not in new_roots:                                new_roots.add(k)                                k = (k + (new_base // p)) % new_base                        roots_in_base = new_roots                    tot_roots = tot_roots | roots_in_base        dd[pow(p, e)] = tot_roots    a = []    m = []    for x, y in dd.items():        m.append(x)        a.append(list(y))    return sorted(set(crt(m, list(i))[0] for i in cartes(*a)))</ins>  def nthroot_mod(a, n, p, all_roots=False):     """


Question: nthrootmod function misses one root of x = 0 mod p. When in the equation x*n = a mod p , when a % p == 0. Then x = 0 mod p is also a root of this equation. But right now does not check for this condition. has a root . But it does not return it.

if n == 2:         return sqrt_mod(a, p, all_roots)     # see Hackman "Elementary Number Theory" (2009), page 76    if not isprime(p):        return _nthroot_mod_composite(a, n, p)    if a % p == 0:        return [0]     if not is_nthpow_residue(a, n, p):         return None    if not isprime(p):        raise NotImplementedError("Not implemented for composite p")     if (p - 1) % n == 0:         return _nthroot_mod1(a, n, p, all_roots)     # The roots of ``x**n - a = 0 (mod p)`` are roots of


Question: ImageSet(Lambda(n, n**2), S.Integers).intersect(S.Integers) raises AttributeError This is in the related intersection code. See also: , and

# diophantine equations f(n)=g(m).     # If the solutions for n are {h(t) : t in Integers} then we return     # {f(h(t)) : t in integers}.    # If the solutions for n are {n_1, n_2, ..., n_k} then we return    # {f(n_i) : 1 <= i <= k}.     if base_set is S.Integers:         gm = None         if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):             gm = other.lamda.expr            m = other.lamda.variables[0]            var = other.lamda.variables[0]            # Symbol of second ImageSet lambda must be distinct from first            m = Dummy('m')            gm = gm.subs(var, m)         elif other is S.Integers:            m = gm = Dummy('x')            m = gm = Dummy('m')         if gm is not None:             fn = self.lamda.expr             n = self.lamda.variables[0]            solns = list(diophantine(fn - gm, syms=(n, m)))            try:                solns = list(diophantine(fn - gm, syms=(n, m), permute=True))            except (TypeError, NotImplementedError):                # TypeError if equation not polynomial with rational coeff.                # NotImplementedError if correct format but no solver.                return            # 3 cases are possible for solns:            # - empty set,            # - one or more parametric (infinite) solutions,            # - a finite number of (non-parametric) solution couples.            # Among those, there is one type of solution set that is            # not helpful here: multiple parametric solutions.             if len(solns) == 0:                 return EmptySet            elif len(solns) != 1:                return            elif any(not isinstance(s, int) and s.free_symbols                     for tupl in solns for s in tupl):                if len(solns) == 1:                    soln, solm = solns[0]                    (t,) = soln.free_symbols                    expr = fn.subs(n, soln.subs(t, n)).expand()                    return imageset(Lambda(n, expr), S.Integers)                else:                    return             else:                soln, solm = solns[0]                (t,) = soln.free_symbols                expr = fn.subs(n, soln.subs(t, n))                return imageset(Lambda(n, expr), S.Integers)                return FiniteSet(*(fn.subs(n, s[0]) for s in solns))      if other == S.Reals:         from sympy.solvers.solveset import solveset_realdiff --git a/sympy/solvers/diophantine.py b/sympy/solvers/diophantine.py-- a/sympy/solvers/diophantine.py++ b/sympy/solvers/diophantine.py


Question: ImageSet(Lambda(n, n**2), S.Integers).intersect(S.Integers) raises AttributeError This is in the related intersection code. See also: , and

else:             raise TypeError     except (TypeError, NotImplementedError):        terms = factor_list(eq)[1]        fl = factor_list(eq)        if fl[0].is_Rational and fl[0] != 1:            return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)        terms = fl[1]      sols = set([])


Question: raises instead of returning The problem is Here raises but probably a should be returned by instead. The obvious result of here is Originally posted by in

def _eval_as_set(self):         # self is univariate and periodicity(self, x) in (0, None)         from sympy.solvers.inequalities import solve_univariate_inequality        from sympy.sets.conditionset import ConditionSet         syms = self.free_symbols         assert len(syms) == 1         x = syms.pop()        return solve_univariate_inequality(self, x, relational=False)        try:            xset = solve_univariate_inequality(self, x, relational=False)        except NotImplementedError:            # solve_univariate_inequality raises NotImplementedError for            # unsolvable equations/inequalities.            xset = ConditionSet(x, self, S.Reals)        return xset      @property     def binary_symbols(self):


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

"gothic_re_im": False,         "decimal_separator": "period",         "perm_cyclic": True,<ins>        "parenthesize_super": True,</ins>         "min": None,         "max": None,     }  # type: Dict[str, Any]


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

def parenthesize_super(self, s):         """ Parenthesize s if there is a superscript in s"""        if "^" in s:        if "^" in s and self._settings['parenthesize_super']:             return r"\left({}\right)".format(s)        elif "^" in s and not self._settings['parenthesize_super']:            return self.embed_super(s)         return s      def embed_super(self, s):


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

p, q = expr.exp.p, expr.exp.q             # issue #12886: add parentheses for superscripts raised to powers             if '^' in base and expr.base.is_Symbol:                base = r"\left(%s\right)" % base                base = self.parenthesize_super(base)             if expr.base.is_Function:                 return self._print(expr.base, exp="%s/%s" % (p, q))             return r"%s^{%s/%s}" % (base, p, q)


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

# to powers         base = self.parenthesize(expr.base, PRECEDENCE['Pow'])         if '^' in base and expr.base.is_Symbol:            base = r"\left(%s\right)" % base            base = self.parenthesize_super(base)         elif (isinstance(expr.base, Derivative)             and base.startswith(r'\left(')             and re.match(r'\\left\(\\d?d?dot', base)


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

else:                     name = r"\operatorname{%s}^{-1}" % func             elif exp is not None:                name = r'%s^{%s}' % (self._hprint_Function(func), exp)                func_tex = self._hprint_Function(func)                func_tex = self.parenthesize_super(func_tex)                name = r'%s^{%s}' % (func_tex, exp)             else:                 name = self._hprint_Function(func)


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

mat_delim="[", mat_str=None, mode="plain", mul_symbol=None,           order=None, symbol_names=None, root_notation=True,           mat_symbol_style="plain", imaginary_unit="i", gothic_re_im=False,          decimal_separator="period", perm_cyclic=True):          decimal_separator="period", perm_cyclic=True, parenthesize_super=True):     r"""Convert the given expression to LaTeX string representation.      Parameters


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

when ``comma`` is specified. Lists, sets, and tuple are printed with semicolon         separating the elements when ``comma`` is chosen. For example, [1; 2; 3] when         ``comma`` is chosen and [1,2,3] for when ``period`` is chosen.<ins>    parenthesize_super : boolean, optional        If set to ``False``, superscripted expressions will not be parenthesized when        powered. Default is ``True``, which parenthesizes the expression when powered.</ins>     min: Integer or None, optional         Sets the lower bound for the exponent to print floating point numbers in         fixed-point format.


Question: Un-parenthesize superscripted symbol Let's think of these superscripted symbols, x^{i}, x^{} <img src="^{i},&space;x^{}" title="x^{i}, x^{}" /Currently, SymPy parenthesizes these symbols when they are taken to power: \left(x^{i}\right)^{2}, \left(x^{}\right)^{2} <img src="\left(x^{i}\right)^{2},&space;\left(x^{}\right)^{2}" title="\left(x^{i}\right)^{2}, \left(x^{}\right)^{2}" /However, LaTeX has its own way to represent these symbols without parentheses by nesting them: {x^{i}}^{2}, {x^{}}^{2} <img src="{x^{i}}^{2},&space;{x^{}}^{2}" title="{x^{i}}^{2}, {x^{}}^{2}" /These are distinguised from 'powered superscription's, which are: x^{i^{2}}, x^{\^{2}} <img src="^{i^{2}},&space;x^{^{2}}" title="x^{i^{2}}, x^{^{2}}" /Then, shouldn't it be better to print them without parentheses? As far as I know, that is the conventional way to print power of superscripted symbols. In , you can see that nabla sign is superscripted then powered without any parenthesis: {\nabla^{}}^{2} <img src="{\nabla^{}}^{2}" title="{\nabla^{*}}^{2}" /

'gothic_re_im': gothic_re_im,         'decimal_separator': decimal_separator,         'perm_cyclic' : perm_cyclic,<ins>        'parenthesize_super' : parenthesize_super,</ins>         'min': min,         'max': max,     }


Question: [WIP] Additional matrix support for NumPy printer <!-- 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 . Please also write a comment on that issue linking back to this pull request once it is open. -- Adds support for the following matrix expressions to the NumPy printer: [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] <!-- 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 --printing numpy printer support for more matrix expressions <!-- END RELEASE NOTES --

self._print(expr.matrix),                                self._print(expr.vector)) <ins>    def _print_ZeroMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.zeros'),            self._print(expr.shape))    def _print_OneMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.ones'),            self._print(expr.shape))    def _print_FunctionMatrix(self, expr):        from sympy.core.function import Lambda        from sympy.abc import i, j        lamda = expr.lamda        if not isinstance(lamda, Lambda):            lamda = Lambda((i, j), lamda(i, j))        return '{}(lambda {}: {}, {})'.format(self._module_format('numpy.fromfunction'),            ', '.join(self._print(arg) for arg in lamda.args[0]),            self._print(lamda.args[1]), self._print(expr.shape))    def _print_HadamardProduct(self, expr):        func = self._module_format('numpy.multiply')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_KroneckerProduct(self, expr):        func = self._module_format('numpy.kron')        return ''.join('{}({}, '.format(func, self._print(arg)) \            for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]),            ')' * (len(expr.args) - 1))    def _print_Adjoint(self, expr):        return '{}({}({}))'.format(            self._module_format('numpy.conjugate'),            self._module_format('numpy.transpose'),            self._print(expr.args[0]))    def _print_DiagonalOf(self, expr):        vect = '{}({})'.format(            self._module_format('numpy.diag'),            self._print(expr.arg))        return '{}({}, (-1, 1))'.format(            self._module_format('numpy.reshape'), vect)    def _print_DiagMatrix(self, expr):        return '{}({})'.format(self._module_format('numpy.diagflat'),            self._print(expr.args[0]))    def _print_DiagonalMatrix(self, expr):        return '{}({}, {}({}, {}))'.format(self._module_format('numpy.multiply'),            self._print(expr.arg), self._module_format('numpy.eye'),            self._print(expr.shape[0]), self._print(expr.shape[1]))</ins>     def _print_Piecewise(self, expr):         "Piecewise function printer"         exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))


Question: () should return objects with no args instead of subclasses of Atom with no arguments returns subclasses of in . But the correct definition of a leaf node should be that it has no . This should be easy to fix, but one needs to check that this doesn't affect the performance.

if types:             types = tuple(                 [t if isinstance(t, type) else type(t) for t in types])        nodes = preorder_traversal(self)        if types:            result = {node for node in nodes if isinstance(node, types)}         else:            types = (Atom,)        result = set()        for expr in preorder_traversal(self):            if isinstance(expr, types):                result.add(expr)            result = {node for node in nodes if not node.args}         return result      @property


Question: combinatorics.Permutation - exception not raised if wrong size is passed to constructor If I create object from list, which length is greater than argument, then the argument is ignored (and exception is not raised): Is there any reason for such behaviour? It seems to me that it would be better to raise an exception.

if isinstance(a, Cycle):  # f                 return cls._af_new(a.list(size))             if not is_sequence(a):  # b<ins>                if size is not None and a + 1 > size:                    raise ValueError('size is too small when max is %s' % a)</ins>                 return cls._af_new(list(range(a + 1)))             if has_variety(is_sequence(ai) for ai in a):                 ok = False


Question: combinatorics.Permutation - exception not raised if wrong size is passed to constructor If I create object from list, which length is greater than argument, then the argument is ignored (and exception is not raised): Is there any reason for such behaviour? It seems to me that it would be better to raise an exception.

raise ValueError('there were repeated elements.')         temp = set(temp)         if not is_cycle and \                any(i not in temp for i in range(len(temp))):            raise ValueError("Integers 0 through %s must be present." %                             max(temp))        if not is_cycle:            if any(i not in temp for i in range(len(temp))):                raise ValueError('Integers 0 through %s must be present.' %                max(temp))            if size is not None and temp and max(temp) + 1 > size:                raise ValueError('max element should not exceed %s' % (size - 1))          if is_cycle:             # it's not necessarily canonical so we won't storediff --git a/sympy/matrices/common.py b/sympy/matrices/common.py-- a/sympy/matrices/common.py++ b/sympy/matrices/common.py


Question: combinatorics.Permutation - exception not raised if wrong size is passed to constructor If I create object from list, which length is greater than argument, then the argument is ignored (and exception is not raised): Is there any reason for such behaviour? It seems to me that it would be better to raise an exception.

isinstance(perm[0], Iterable):             if direction == 'forward':                 perm = list(reversed(perm))            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)         else:            perm = Permutation(perm, size=max_index)            perm = Permutation(perm, size=max_index+1)          if orientation == 'rows':             return self._eval_permute_rows(perm)


Question: Idx object can accepts non-integer bounds It is my understanding that this code should not work: the lower and upper bounds should be integers. Instead it runs without any errors: Note however that: produces the expected result: The check for integer dimension should be done to both upper and lower bounds when a tuple is given as argument.

from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.compatibility import (is_sequence, NotIterable,                                       Iterable)from sympy.core.logic import fuzzy_boolfrom sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta


Question: Idx object can accepts non-integer bounds It is my understanding that this code should not work: the lower and upper bounds should be integers. Instead it runs without any errors: Note however that: produces the expected result: The check for integer dimension should be done to both upper and lower bounds when a tuple is given as argument.

raise TypeError("Idx object requires integer bounds.")             args = label, Tuple(*range)         elif isinstance(range, Expr):            if not (range.is_integer or range is S.Infinity):            if range is not S.Infinity and fuzzy_not(range.is_integer):                 raise TypeError("Idx object requires an integer dimension.")             args = label, Tuple(0, range - 1)         elif range:


Question: BlockDiagMatrix with one element cannot be converted to regular Matrix Creating a BlockDiagMatrix with one Matrix element will raise if trying to convert it back to a regular Matrix: Instead having two elements will work as expected: This issue exists for sympy 1.5.1 but not for sympy 1.4

data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)                         for j in range(len(mats))]                         for i in range(len(mats))]        return ImmutableDenseMatrix(data)        return ImmutableDenseMatrix(data, evaluate=False)      @property     def shape(self):


Question: AttributeError: integrate(1 / (1 + x4)(S(1)/4), [x, 0, oo]) It is trying to compute the of a hypergeometric function:

return Piecewise((Sum(coeff * z**n / factorial(n), (n, 0, oo)),                          self.convergence_statement), (self, True)) <ins>    def _eval_nseries(self, x, n, logx):        from sympy.functions import factorial, RisingFactorial        from sympy import Order, Add        arg = self.args[2]        x0 = arg.limit(x, 0)        ap = self.args[0]        bq = self.args[1]        if x0 != 0:            return super(hyper, self)._eval_nseries(x, n, logx)        terms = []        for i in range(n):            num = 1            den = 1            for a in ap:                num *= RisingFactorial(a, i)            for b in bq:                den *= RisingFactorial(b, i)            terms.append(((num/den) * (arg**i)) / factorial(i))        return (Add(*terms) + Order(x**n,x))</ins>     @property     def argument(self):         """ Argument of the hypergeometric function. """


Question: Random test failing in testtensorpartial_deriv It happened in I suspect the problem is the random value sometimes get zero and doesn't evaluate.

expr = expr.expr          args, indices, free, dum = cls._contract_indices_for_derivative(            expr, variables)            S(expr), variables)          obj = TensExpr.__new__(cls, *args)


Question: Random test failing in testtensorpartial_deriv It happened in I suspect the problem is the random value sometimes get zero and doesn't evaluate.

result = obj         if isinstance(obj.expr, TensAdd):        if not args[0].free_symbols:            return S.Zero        elif isinstance(obj.expr, TensAdd):             # take care of sums of multi PDs             result = obj.expr.func(*[                     self.func(a, *obj.variables)._expand_partial_derivative()


Question: sqrt(8)**Rational(2, 3) doesn't simplify The results should just be .

rv = S.One         if cargs:<ins>            if e.is_Rational:                npow, cargs = sift(cargs, lambda x: x.is_Pow and                    x.exp.is_Rational and x.base.is_number,                    binary=True)                rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])</ins>             rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])         if other:             rv *= self.func(Mul(*other), e, evaluate=False)


Question: Added new feature SchurNumber <!-- I have a new feature in the combinatorics module the Schurnumber --The Schur number S(k) is the largest integer n for which the interval [1,n] can be partitioned into k sum-free sets. I have also made the partition which can be proven by induction and I have test cases

<ins>"""The Schur number S(k) is the largest integer n for which the interval [1,n]can be partitioned into k sum-free sets.(http://mathworld.wolfram.com/SchurNumber.html)"""import mathfrom sympy.core import Sfrom sympy.core.basic import Basicfrom sympy.core.function import Functionfrom sympy.core.numbers import Integerclass SchurNumber(Function):    """    This function creates a SchurNumber object    which is evaluated for k <= 4 otherwise only    the lower bound information can be retrieved.    Examples    ========    >>> from sympy.combinatorics.schur_number import SchurNumber    Since S(3) = 13, hence the output is a number    >>> SchurNumber(3)    13    We don't know the schur number for values greater than 4, hence    only the object is returned    >>> SchurNumber(6)    SchurNumber(6)    Now, the lower bound information can be retrieved using lower_bound()    method    >>> SchurNumber(6).lower_bound()    364    """    @classmethod    def eval(cls, k):        if k.is_Number:            if k is S.Infinity:                return S.Infinity            if k.is_zero:                return 0            if not k.is_integer or k.is_negative:                raise ValueError("k should be a positive integer")            first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44}            if k <= 4:                return Integer(first_known_schur_numbers[k])    def lower_bound(self):        f_ = self.args[0]        return (3**f_ - 1)/2def _schur_subsets_number(n):    if n is S.Infinity:        raise ValueError("Input must be finite")    if n <= 0:        raise ValueError("n must be a non-zero positive integer.")    elif n <= 3:        min_k = 1    else:        min_k = math.ceil(math.log(2*n + 1, 3))    return Integer(min_k)def schur_partition(n):    """    This function returns the partition in the minimum number of sum-free subsets    according to the lower bound given by the Schur Number.    Parameters    ==========    n: a number        n is the upper limit of the range [1, n] for which we need to find and        return the minimum number of free subsets according to the lower bound        of schur number    Returns    =======    List of lists        List of the minimum number of sum-free subsets    Notes    =====    It is possible for some n to make the partition into less    subsets since the only known Schur numbers are:    S(1) = 1, S(2) = 4 , S(3) = 13, S(4) = 44.    e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven    that can be done with 4 subsets.    Examples    ========    For n = 1, 2, 3 the answer is the set itself    >>> from sympy.combinatorics.schur_number import schur_partition    >>> schur_partition(2)    [[1, 2]]    For n > 3, the answer is the minimum number of sum-free subsets:    >>> schur_partition(5)    [[3, 2], [5], [1, 4]]    >>> schur_partition(8)    [[3, 2], [6, 5, 8], [1, 4, 7]]    """    if isinstance(n, Basic) and not n.is_Number:        raise ValueError("Input value must be a number")    number_of_subsets = _schur_subsets_number(n)    if n == 1:        sum_free_subsets = [[1]]    elif n == 2:        sum_free_subsets = [[1, 2]]    elif n == 3:        sum_free_subsets = [[1, 2, 3]]    else:        sum_free_subsets = [[1, 4], [2, 3]]    while len(sum_free_subsets) < number_of_subsets:        sum_free_subsets = _generate_next_list(sum_free_subsets, n)        missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)]        sum_free_subsets[-1] += missed_elements    return sum_free_subsetsdef _generate_next_list(current_list, n):    new_list = []    for item in current_list:        temp_1 = [number*3 for number in item if number*3 <= n]        temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n]        new_item = temp_1 + temp_2        new_list.append(new_item)    last_list = [3*k + 1 for k in range(0, len(current_list)+1) if 3*k + 1 <= n]    new_list.append(last_list)    current_list = new_list    return current_list</ins>


Question: sqf and sqflist output is not consistant The example below is wrong in the sense that we should have (x*2 - 5_x + 6, 3) and not 2 factors of multiplicity 3. whereas below is correct --- one factor of multiplicity 2

from __future__ import print_function, division from functools import wrapsfrom functools import wraps, reducefrom operator import mul  from sympy.core import (     S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple


Question: sqf and sqflist output is not consistant The example below is wrong in the sense that we should have (x*2 - 5_x + 6, 3) and not 2 factors of multiplicity 3. whereas below is correct --- one factor of multiplicity 2

if arg.is_Number:             coeff *= arg             continue        if arg.is_Mul:            args.extend(arg.args)            continue        if arg.is_Pow:        elif arg.is_Pow:             base, exp = arg.args             if base.is_Number and exp.is_Number:                 coeff *= arg


Question: sqf and sqflist output is not consistant The example below is wrong in the sense that we should have (x*2 - 5_x + 6, 3) and not 2 factors of multiplicity 3. whereas below is correct --- one factor of multiplicity 2

other.append((f, k))                  factors.append((_factors_product(other), exp))<ins>    if method == 'sqf':        factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k)                   for k in set(i for _, i in factors)]</ins>      return coeff, factors


Question: Fix iszero and ispositive for Pow <!-- 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 . Please also write a comment on that issue linking back to this pull request once it is open. -- Still a work in progress. This attempts to get working in all cases. This PR fixes so that it doesn't assume finiteness unless justified by assumptions. For example on master: This is incorrect because if a or b can be infinite then it is possible for to be zero e.g. if is infinite and b is negative (a)<1 and b is positive infinite (oo) (a)1 and b is negative infinite (-oo) With this PR we have meaning that could be zero or could not be zero. Also on master we have whereas this PR gives in that case since could be zero and therefore not be positive. This PR also since This comes from the fact that is properly considered nonzero if is declared as finite. At the time of writing we still have this problem with the PR though: I'm not sure that this PR should be merged as is. Many of the changes are adding flags that probably shouldn't be there. Those flags would not be necessary if the other assumptions implied finite=True. For example in some cases a symbol is declared as and with this PR I've had to add also. Probably it would be better to fix those cases by having in the assumptions system. Most of the other cases are for symbols declared as which could also be fixed. Now that I (hopefully) have the tests passing I still want to improve this PR by tidying up the implementation. Also it still doesn't work in all cases as the zoo/n example above shows. Perhaps instead of merging this I could build new PRs on top. One could add . Then I could follow that with splitting real into extendedreal and real and having as well. That would be a big change though so maybe it would be better to merge this first. <!-- 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 --core Fix iszero assumptions for and when or could be infinite. <!-- END RELEASE NOTES --

elif self.exp.is_extended_nonpositive:                 return False         elif self.base.is_zero is False:            if self.exp.is_negative:            if self.base.is_finite and self.exp.is_finite:                return False            elif self.exp.is_negative:                 return self.base.is_infinite             elif self.exp.is_nonnegative:                 return False            elif self.exp.is_infinite:            elif self.exp.is_infinite and self.exp.is_extended_real:                 if (1 - abs(self.base)).is_extended_positive:                     return self.exp.is_extended_positive                 elif (1 - abs(self.base)).is_extended_negative:                     return self.exp.is_extended_negative        else:            # when self.base.is_zero is None            return None        else: # when self.base.is_zero is None            if self.base.is_finite and self.exp.is_negative:                return False      def _eval_is_integer(self):         b, e = self.args


Question: Fix iszero and ispositive for Pow <!-- 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 . Please also write a comment on that issue linking back to this pull request once it is open. -- Still a work in progress. This attempts to get working in all cases. This PR fixes so that it doesn't assume finiteness unless justified by assumptions. For example on master: This is incorrect because if a or b can be infinite then it is possible for to be zero e.g. if is infinite and b is negative (a)<1 and b is positive infinite (oo) (a)1 and b is negative infinite (-oo) With this PR we have meaning that could be zero or could not be zero. Also on master we have whereas this PR gives in that case since could be zero and therefore not be positive. This PR also since This comes from the fact that is properly considered nonzero if is declared as finite. At the time of writing we still have this problem with the PR though: I'm not sure that this PR should be merged as is. Many of the changes are adding flags that probably shouldn't be there. Those flags would not be necessary if the other assumptions implied finite=True. For example in some cases a symbol is declared as and with this PR I've had to add also. Probably it would be better to fix those cases by having in the assumptions system. Most of the other cases are for symbols declared as which could also be fixed. Now that I (hopefully) have the tests passing I still want to improve this PR by tidying up the implementation. Also it still doesn't work in all cases as the zoo/n example above shows. Perhaps instead of merging this I could build new PRs on top. One could add . Then I could follow that with splitting real into extendedreal and real and having as well. That would be a big change though so maybe it would be better to merge this first. <!-- 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 --core Fix iszero assumptions for and when or could be infinite. <!-- END RELEASE NOTES --

if real_b is False:  # we already know it's not imag             i = arg(self.base)*self.exp/S.Pi            return i.is_integer            if i.is_complex: # finite                return i.is_integer      def _eval_is_complex(self):


Question: Incorrect parenthesizing of Subs Here is an example. LaTeX printing of this gives: ! It would be better to be parenthesized to: !

latex_new = (self._print(e) for e in new)         latex_subs = r'\\ '.join(             e[0] + '=' + e[1] for e in zip(latex_old, latex_new))        return r'\left. %s \right|_{\substack{ %s }}' % (latex_expr,        return r'\left. \left(%s\right) \right|_{\substack{ %s }}' % (latex_expr,                                                          latex_subs)      def _print_Integral(self, expr):


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

"""     is_HadamardProduct = True     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         args = list(map(sympify, args))         check = kwargs.get('check', True)         if check:             validate(*args)         return super(HadamardProduct, cls).__new__(cls, *args)        obj = super(HadamardProduct, cls).__new__(cls, *args)        if evaluate:            obj = obj.doit(deep=False)        return obj      @property     def shape(self):diff --git a/sympy/matrices/expressions/matadd.py b/sympy/matrices/expressions/matadd.py-- a/sympy/matrices/expressions/matadd.py++ b/sympy/matrices/expressions/matadd.py


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

identity = GenericZeroMatrix()     def __new__(cls, *args, **kwargs):    def __new__(cls, *args, evaluate=False, **kwargs):         if not args:             return cls.identity


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

check = kwargs.get('check', False)          obj = Basic.__new__(cls, *args)         if check:             if all(not isinstance(i, MatrixExpr) for i in args):                 return Add.fromiter(args)             validate(*args)        if evaluate:            if all(not isinstance(i, MatrixExpr) for i in args):                return Add(*args, evaluate=True)            obj = canonicalize(obj)         return obj      @propertydiff --git a/sympy/matrices/expressions/matmul.py b/sympy/matrices/expressions/matmul.py-- a/sympy/matrices/expressions/matmul.py++ b/sympy/matrices/expressions/matmul.py


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

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


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

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


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

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: generate_derangements mishandles unsorted perm The following is incorrect: The routine is assuming that the is sorted (though this is not a requirement):

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


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

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


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

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

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)


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

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:


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

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: 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. !

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: 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. !

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: 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. !

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: 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. !

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

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


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

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

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

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


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

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

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


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

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)


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

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:


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

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

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

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

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


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

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


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

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

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


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

+ '_{%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: 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]

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

+ '[%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: 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.

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]`. """


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

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


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

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?


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

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


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

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

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

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

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


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

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:


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

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:


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

"""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__ = [


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

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: Dagger() * IdentityOperator() is not simplified As discussed on the mailing list the following does not work.

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


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

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,


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

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)