Question: elif parts[0] == 'type':             name = ' '.join(parts[1:])             has_type.add(name)        elif parts[0] == 'return':        elif parts[0] in ('return', 'returns'):             has_description.add('return')         elif parts[0] == 'rtype':             has_type.add('return')      # Add 'type' for parameters with a description but no declared type.     for name in annotations:        if name == 'return':        if name in ('return', 'returns'):             continue         if name in has_description and name not in has_type:             field = nodes.field()

autodoctypehintsdescriptiontarget not working with Napoleon I was trying to use the config option combined with the Napoleon plugin (using Google style). The return types were missing from the resulting documentation. Just generate the documentation using Napoleon and the config options: Generate the documentation of a function with the following docstring: As the return is specified, the return type should be present in the documentation, either as a rtype section or as part of the return description. ! Win 8 0 '', '', '', '', '', No response No response


Question: if 'classmethod' in self.options:             return _('%s() (%s class method)') % (methname, clsname)         elif 'property' in self.options:            return _('%s() (%s property)') % (methname, clsname)            return _('%s (%s property)') % (methname, clsname)         elif 'staticmethod' in self.options:             return _('%s() (%s static method)') % (methname, clsname)         else:

An index entry with parens was registered for directive with option An index entry with parens was registered for directive with option. It should not have parens. An index entry for the property should not have parens. N/A <img width="528" alt=" 2021-10-03 13 00 53" src="https://user-"Mac 6 HEAD of 4.x No response No response No response


Question: from typing import TYPE_CHECKING, Any, Dict <ins>from packaging.version import InvalidVersion, Version</ins> from sphinx.config import Config from sphinx.errors import VersionRequirementError from sphinx.locale import __

needsextensions checks versions using strings The check is handy for verifying minimum extension versions, but it only checks versions in a 'string-like' manner. This means any version 9 is not allowed for any check of something 1. That is, treated as string '0.6' '0.10', but treated as versions '0.6' < '0.10'. Since Sphinx does the former, some extension versions may not be allowed when they should be. This passes just fine, because the requirements pin sphinx-gallery to 0.9. But if you then update to the current 0.10 release: results in a failure due to a "not new enough" version: sphinx-gallery 0.10.0 should be accepted if 0.6 is the minimum specified. No response Fedora 6 2 No response No response No response


Question: 'but it is not loaded.'), extname)             continue         if extension.version == 'unknown version' or reqversion > extension.version:        fulfilled = True        if extension.version == 'unknown version':            fulfilled = False        else:            try:                if Version(reqversion) > Version(extension.version):                    fulfilled = False            except InvalidVersion:                if reqversion > extension.version:                    fulfilled = False        if not fulfilled:             raise VersionRequirementError(__('This project needs the extension %s at least in '                                              'version %s and therefore cannot be built with '                                              'the loaded version (%s).') %


Question: for basecls in getmro(cls):             meth = basecls.__dict__.get(name)             if meth and hasattr(meth, '__func__'):                return getdoc(meth.__func__)                doc = getdoc(meth.__func__)                if doc is not None or not allow_inherited:                    return doc      doc = attrgetter(obj, '__doc__', None)     if ispartial(obj) and doc == obj.__class__.__doc__:

Overridden classmethod documentation not inherited with autodoc The documentation for a classmethod in a parent class is not inherited by the method re-defined (without documentation) in a child class Module : Sphinx configuration : Documentation index : Build: Overridden classmethod to inherit documentation from parent class ! Ubuntu 20.04 8 0 returns the expected value


Question: split_contnode = bool(contnode and contnode.astext() == target)         in_literal = False         results = []         for sub_target in filter(None, sub_targets):             if split_contnode:                 contnode = nodes.Text(sub_target)             if delims_re.match(sub_target):            if in_literal or delims_re.match(sub_target):                 results.append(contnode or innernode(sub_target, sub_target))             else:                 results.append(self.make_xref(rolename, domain, sub_target,                                               innernode, contnode, env, inliner, location))             if sub_target in ('Literal', 'typing.Literal'):                in_literal = True         return results

Nitpick flags Literal annotation values as missing py:class (with type hints in description) This is basically the same issue as , which was fixed in . However, I still get this issue when using . Comment out the line in and it is successful, as shown below (and removing the build artifacts to start fresh). No error, the build should succeed. See attachment in "How to Reproduce" section N/A - output is shown in "How to Reproduce" section Linux and Windows 9 0 , N/A This re-produces for me on both Linux and Windows. I think the source of it issue is probably from in since this function would otherwise be skipped if the type hints are left in the signature. But I haven't yet been able to track it all the way down to the error.


Question: import ast import inspectfrom typing import Any, Dictimport sysfrom typing import Any, Dict, List, Optional  from sphinx.application import Sphinx from sphinx.locale import __

Re-opening : hexadecimal default arguments are changed to decimal I am experiencing the exact same problem as described in : hexadecimal default arguments are changed to decimal. Autodoc the following function: HTML result looks like this Hexadecimal defaults should not be converted to decimal, or at least there should be an option to enforce this behaviour. I'm afraid this is private No response Linux Ubuntu 20.04 10 0 autodoc, intersphinx, napoleon Chromium 94 No response


Question: return None  def get_default_value(lines: List[str], position: ast.AST) -> Optional[str]:    try:        if sys.version_info < (3, 8):  # only for py38+            return None        elif position.lineno == position.end_lineno:            line = lines[position.lineno - 1]            return line[position.col_offset:position.end_col_offset]        else:            # multiline value is not supported now            return None    except (AttributeError, IndexError):        return None def update_defvalue(app: Sphinx, obj: Any, bound_method: bool) -> None:     """Update defvalue info of *obj* using type_comments."""     if not app.config.autodoc_preserve_defaults:         return     try:        lines = inspect.getsource(obj).splitlines()        if lines[0].startswith((' ', r'\t')):            lines.insert(0, '')  # insert a dummy line to follow what get_function_def() does.    except OSError:        lines = []     try:         function = get_function_def(obj)         if function.args.defaults or function.args.kw_defaults:


Question: for i, param in enumerate(parameters):                 if param.default is not param.empty:                     if param.kind in (param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD):                        value = DefaultValue(ast_unparse(defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))                     else:                        value = DefaultValue(ast_unparse(kw_defaults.pop(0)))  # type: ignore                        parameters[i] = param.replace(default=value)                        default = kw_defaults.pop(0)                        value = get_default_value(lines, default)                        if value is None:                            value = ast_unparse(default)  # type: ignore                        parameters[i] = param.replace(default=DefaultValue(value))             sig = sig.replace(parameters=parameters)             obj.__signature__ = sig     except (AttributeError, TypeError):


Question: self.config.language, self.config.source_encoding)             for catalog in repo.catalogs:                 if catalog.domain == 'sphinx' and catalog.is_outdated():                    catalog.write_mo(self.config.language)                    catalog.write_mo(self.config.language,                                     self.config.gettext_allow_fuzzy_translations)              locale_dirs: List[Optional[str]] = list(repo.locale_dirs)             locale_dirs += [None]diff --git a/sphinx/builders/__init__.py b/sphinx/builders/__init__.py-- a/sphinx/builders/__init__.py++ b/sphinx/builders/__init__.py

Support for fuzzy translations Problem Entries in po files that are currently marked as "fuzzy" are not used in "mo" files. The original source language is used instead of the translated language. Fuzzy translations are translations that in general need to be reviewed by a translator. For example all machine translations could be marked as fuzzy. It would be desirable to let the user decide whether to include these fuzzy translations in the generated documentation. Proposed solution Add a new configuration parameter "usefuzzytranslations". Change in line 72 of the file writemo(filemo, po) to writemo(filemo, po, usefuzzytranslations) Writing mo files with fuzzy translations is supported by the babel package, as can be seen in the documentation:


Question: for catalog in status_iterator(catalogs, __('writing output... '), "darkgreen",                                        len(catalogs), self.app.verbosity,                                        stringify_func=cat2relpath):            catalog.write_mo(self.config.language)            catalog.write_mo(self.config.language,                             self.config.gettext_allow_fuzzy_translations)      def compile_all_catalogs(self) -> None:         repo = CatalogRepository(self.srcdir, self.config.locale_dirs,diff --git a/sphinx/config.py b/sphinx/config.py-- a/sphinx/config.py++ b/sphinx/config.py


Question: 'language': (None, 'env', [str]),         'locale_dirs': (['locales'], 'env', []),         'figure_language_filename': ('{root}.{language}{ext}', 'env', [str]),        'gettext_allow_fuzzy_translations': (False, 'gettext', []),          'master_doc': ('index', 'env', []),         'root_doc': (lambda config: config.master_doc, 'env', []),diff --git a/sphinx/util/i18n.py b/sphinx/util/i18n.py-- a/sphinx/util/i18n.py++ b/sphinx/util/i18n.py


Question: not path.exists(self.mo_path) or             path.getmtime(self.mo_path) < path.getmtime(self.po_path))     def write_mo(self, locale: str) -> None:    def write_mo(self, locale: str, use_fuzzy: bool = False) -> None:         with open(self.po_path, encoding=self.charset) as file_po:             try:                 po = read_po(file_po, locale)


Question: with open(self.mo_path, 'wb') as file_mo:             try:                write_mo(file_mo, po)                write_mo(file_mo, po, use_fuzzy)             except Exception as exc:                 logger.warning(__('writing error: %s, %s'), self.mo_path, exc)


Question: domain = cast(MathDomain, app.env.get_domain('math'))     if app.registry.html_assets_policy == 'always' or domain.has_equations(pagename):         # Enable mathjax only if equations exists        options = {'async': 'async'}        options = {'defer': 'defer'}         if app.config.mathjax_options:             options.update(app.config.mathjax_options)         app.add_js_file(app.config.mathjax_path, **options)  # type: ignore

Add a way to defer loading of MathJax Is your feature request related to a problem? Please describe. It is quite tricky to configure MathJax to work with Sphinx currently. Sphinx loads MathJax asynchronously since and While this was fine for MathJax 2, because of the special kind of blocks mentioned in , it doesn't work well with MathJax 3. Indeed, in MathJax 3, MathJax expect a config block to be present before MathJax is loaded. Sphinx 4 parameter: This assumes that the is a simple dictionary, which isn't sufficient: that configuration should be able to contain functions, for example. The only possibility at the moment is to add a separate script file containing a MathJax configuration and to load it with. Describe the solution you'd like There are three possibilities: Allow arbitrary strings for mathjax3config, and in that case don't JSON-serialize them. Change to when loading MathJax. Make it possible for users to change to themselves. At the moment this isn't possible because the flags is unconditionally : The latter two are preferable because they would allow individual pages to use different MathJax config by using a block to override the default MathJax configuration on a given page (the script in that defer` option). CC , the author of . Thanks!


Question: deprecated: bool  def type_to_xref(text: str, env: BuildEnvironment = None) -> addnodes.pending_xref:def type_to_xref(target: str, env: BuildEnvironment = None) -> addnodes.pending_xref:     """Convert a type string to a cross reference node."""    if text == 'None':    if target == 'None':         reftype = 'obj'     else:         reftype = 'class'

.. py:data:: :type: option does not correctly link to type supplied when using the .. py:data:: directive there is the :type: option to specify the type for the data being stored in the module level attribute. It does not work within the context of the module. What I mean by that is I have to key out the entire module path and the class for the type instead of importing the type into the module and only having to type in the type class name. say I have the following in the module "mylibrary.module1" The output I get when building the docs is this. and "Unit" is not a clickable link. However if I have the following in the module "mylibrary.module1" I get this for an output and "mylibrary.module2.Unit" is a clickable link that brings up the documentation for the Unit class to be able to do the following and have the output be and "Unit" be a clickable link that leads to the class that is specified in :type: No response Windows 8 2 No response No response


Question: else:         kwargs = {} <ins>    refspecific = False    if target.startswith('.'):        target = target[1:]        text = target        refspecific = True    elif target.startswith('~'):        target = target[1:]        text = target.split('.')[-1]    else:        text = target</ins>     if env.config.python_use_unqualified_type_names:         # Note: It would be better to use qualname to describe the object to support support         # nested classes.  But python domain can't access the real python object because this


Question: contnodes = [nodes.Text(text)]      return pending_xref('', *contnodes,                        refdomain='py', reftype=reftype, reftarget=text, **kwargs)                        refdomain='py', reftype=reftype, reftarget=target,                        refspecific=refspecific, **kwargs)   def _parse_annotation(annotation: str, env: BuildEnvironment = None) -> List[Node]:


Question: class SphinxWarningLogRecord(SphinxLogRecord):     """Warning log record class supporting location"""    prefix = 'WARNING: '    @property    def prefix(self) -> str:  # type: ignore        if self.levelno >= logging.CRITICAL:            return 'CRITICAL: '        elif self.levelno >= logging.ERROR:            return 'ERROR: '        else:            return 'WARNING: '   class SphinxLoggerAdapter(logging.LoggerAdapter):

Different build warnings are colored differently Some types of warnings seem to be different colors than others. An image warning is light red, a transition warning is dark red. This behavior exists regardless of being set. Use the branch specified. I purposely broke an image's path to showcase the differently-colored warning so it's not on main or develop. Based on , I'd expect all warnings to have the same color, and to not match the color of errors. ! macOS 10.15.7 (Catalina) 7 Sphinx v4.1.2 No response No response No response


Question: """Returns the name of the first argument if in a function."""         if self.current_function and self.current_function.args.args:             return self.current_function.args.args[0]<ins>        elif (self.current_function and              getattr(self.current_function.args, 'posonlyargs', None)):            # for py38+            return self.current_function.args.posonlyargs[0]  # type: ignore</ins>         else:             return None

Using position-only parameter syntax in prevents docstrings for attributes from being parsed I'm currently using in most of my functions, including , however this prevents inline, before, and after doc strings from being parsed. Once is open, you will see that only has the property documented. Both classes should have the property documented <img width="636" alt="image" src="https://user-"macOS 11.6.1 10 1 , No response No response


Question: ctx = r'\phantomsection'             for node_id in node['ids']:                 ctx += self.hypertarget(node_id, anchor=False)        ctx += r'}] \leavevmode'        self.body.append(r'\item[{')        ctx += r'}'        self.body.append(r'\sphinxlineitem{')         self.context.append(ctx)      def depart_term(self, node: Element) -> None:

Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response LaTeX: glossary terms with common definition are rendered with too much vertical whitespace as in title and No response see code snippet ! Mac 0 2 Latex: terms are not separated by a newline I use simple indentations for terms and their explanation: Example: Which results in the following HTML output: Alabaster: ! RTD theme: ! While xelatex output does not contain a new line: ! Build the snippet. No response Build the snippet No response Linux 8 0 No response No response No response


Question: return self._print_Add(s.truncate()) + self._print(' + \ldots')      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_FiniteField(self, expr):         return r"\mathbb{F}_{%s}" % expr.moddiff --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

fps should print as a formal power series When I first used , I didn't realize it really was a formal power series as it claims to be, because it prints like a normal series (same as ) But if you look at the string form, you see That is, it really does represent it as the formula (albiet, not simplified). It out to print it like this, so you can see that that's what it's working with. Side question: if you enter something it can't compute, it just returns the function Is that intentional? It seems like it ought to raise an exception in that case.


Question: return self._print_Add(s.truncate()) + self._print(dots)      def _print_FormalPowerSeries(self, s):        return self._print_Add(s.truncate())        return self._print_Add(s.infinite)      def _print_SeqFormula(self, s):         if self._use_unicode:


Question: else:             return name <ins>    def _print_Relational(self, expr):        lhs_code = self._print(expr.lhs)        rhs_code = self._print(expr.rhs)        op = expr.rel_op        return ("{0} {1} {2}").format(lhs_code, op, rhs_code)    def _print_sinc(self, expr):        from sympy.functions.elementary.trigonometric import sin        from sympy.core.relational import Ne        from sympy.functions import Piecewise        _piecewise = Piecewise(            (sin(expr.args[0]) / expr.args[0], Ne(expr.args[0], 0)), (1, True))        return self._print(_piecewise)</ins>     def _print_AugmentedAssignment(self, expr):         lhs_code = self._print(expr.lhs)         op = expr.rel_op

ccode(sinc(x)) doesn't work I don't think has , but it could print


Question: diop_type = "cubic_thue"      elif (total_degree > 3 and total_degree % 2 == 0 and            all(k.is_Pow for k in coeff if k != 1)):            all(k.is_Pow and k.exp == total_degree for k in coeff if k != 1)):         if all(coeff[k] == 1 for k in coeff if k != 1):             diop_type = 'general_sum_of_even_powers'

diophantine: misclassification A check should be made that all powers are the same (not only that they are even).


Question: sqrt(x**2 + y**2)          """<ins>        if type(p) is not type(self):            if len(p) == len(self):                return sqrt(sum([(a - b)**2 for a, b in zip(                    self.args, p.args if isinstance(p, Point) else p)]))            else:                p1 = [0] * max(len(p), len(self))                p2 = p.args if len(p.args) > len(self.args) else self.args                for i in range(min(len(p), len(self))):                    p1[i] = p.args[i] if len(p) < len(self) else self.args[i]                return sqrt(sum([(a - b)**2 for a, b in zip(                    p1, p2)]))</ins>         return sqrt(sum([(a - b)**2 for a, b in zip(             self.args, p.args if isinstance(p, Point) else p)]))

distance calculation wrong The 3rd dimension is being ignored when the Points are zipped together to calculate the distance so is being computed instead of .


Question: >>> cos(_)     0.73908513321516064165531208767387340401341175890076     mpmath.findroot is used, you can find there more extensive documentation,    especially concerning keyword parameters and available solvers. Note,    however, that this routine works only with the numerator of the function    in the one-dimensional case, and for very steep functions near the root    this may lead to a failure in the verification of the root. In this case    you should use the flag `verify=False` and independently verify the    solution.    mpmath.findroot is used and you can find there more extensive    documentation, especially concerning keyword parameters and    available solvers. Note, however, that functions which are very    steep near the root the verification of the solution may fail. In    this case you should use the flag `verify=False` and    independently verify the solution.      >>> from sympy import cos, cosh     >>> from sympy.abc import i

nsolve wrong result Here's a plot of the function in question. As you can see, the root should be around 0.7. !


Question: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1))     >>> nsolve(f, bounds(100), solver='bisect', verify=False)     315.730061685774<ins>    Alternatively, a function may be better behaved when the    denominator is ignored. Since this is not always the case, however,    the decision of what function to use is left to the discretion of    the user.    >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100    >>> nsolve(eq, 0.46)    Traceback (most recent call last):    ...    ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19)    Try another starting point or tweak arguments.    >>> nsolve(eq.as_numer_denom()[0], 0.46)    0.46792545969349058</ins>     """     # there are several other SymPy functions that use method= so     # guard against that here


Question: expected a one-dimensional and numerical function'''))          # the function is much better behaved if there is no denominator        f = f.as_numer_denom()[0]        # but sending the numerator is left to the user since sometimes        # the function is better behaved when the denominator is present        # e.g., issue 11768          f = lambdify(fargs, f, modules)         return Float(findroot(f, x0, **kwargs))


Question: pform = base**n             return pform         else:            return self._print_Function(e)            n = self._print(e.args[2])            shift = self._print(e.args[0]-e.args[1])            base = self._print_seq(shift, "<", ">", ' ')            return base**n      def _print_gamma(self, e):         if self._use_unicode:

ASCII printing for Singularity Function. Implementation of ASCII printing for Singularity Functions is needed.


Question: if end == start and (left_open or right_open):             return S.EmptySet         if end == start and not (left_open or right_open):<ins>            if start == S.Infinity or start == S.NegativeInfinity:                return S.EmptySet</ins>             return FiniteSet(end)          # Make sure infinite interval end points are open.

Where oo belongs? (Concept) Hi again, well, i'm little confuse of the conditions to take or not in some sets: First the means the interval is created excluding and , and interval interpret it in that way, but now: Here is a little conflict, in first place Interval show don't take but now it is there? in some way is fine to have a way to can represent the from Interval. Now from this point we have some points: How they will interpret the limit concept? basically two options, limit is: or ? This point is very important, because define the behavior for sets, and affects directly like this issue: so, for now only to match the math in all sets we can say the limit is calculated via now, what is the effect of this in Sympy?, first this enable the limit concept in every unbounded set, for now i found this two issues: for example, actually we have this: this return should be something like... ? because in the limit we don't know what is the proportion of and , so we can't calc it. actually this concept is applied in some way like: Now the next question, will represent the infinite, as a integer, real or what? i know this question don't have sense, but let me try explain it: if the oo represent the infinite without form, it can exist in S.Naturals, and S.Reals, but if you represent the infinite like the interval between it, where is the limit of x to infinite while always , in other way where A go to and B do to , but it need always will respect this condition so between and can exist any type of numbers, so can't exist in because can contains a real number for example, but the extension of that concept says can't exist in any set, because always will exist a bigger set, in sympy you have an approximation of it, is , but don't will be true completely, because, why is it the limit set?, can represent two things, the limit of the actually human knowledge (or applied to Sympy), or the 'master' set, thinking its like the perfection of the sets knowledge. Obvs, to make some sense in the actual system the option is interpret without limit or form, and take the second interpretation of (if you take the first. can't exist in any place).


Question: if end == start and (left_open or right_open):             return S.EmptySet         if end == start and not (left_open or right_open):<ins>            if start == S.Infinity or start == S.NegativeInfinity:                return S.EmptySet</ins>             return FiniteSet(end)          # Make sure infinite interval end points are open.

If you disagree you always can discuss and change the behavior. Objetives of this issue: Get a clear definitions in Sympy of: Infinite Limit UniversalSet Then, clear the behavior of this concepts in Sympy, and to finish, set the behavior in Sympy. Thx. Cya.


Question: """         return self.sets._measure <ins>    @classmethod    def from_real(cls, sets):        """        Converts given subset of real numbers to a complex region.        Examples        ========        >>> from sympy import Interval, ComplexRegion        >>> unit = Interval(0,1)        >>> ComplexRegion.from_real(unit)        ComplexRegion([0, 1] x {0}, False)        """        if not sets.is_subset(S.Reals):            raise ValueError("sets must be a subset of the real line")        return cls(sets * FiniteSet(0))</ins>     def _contains(self, other):         from sympy.functions import arg, Abs         from sympy.core.containers import Tuple

Union(FiniteSet(oo), S.Complexes) gives S.Complexes (should remain unevaluated) Hi, well searching i found this: i don't know with this where belongs, is part of Complexes or not? Thx. Cya.


Question: return ComplexRegion(new_r_interval*new_theta_interval,                                     polar=True) <del>        if other is S.Reals:            return other</del>          if other.is_subset(S.Reals):             new_interval = []


Question: def _union(self, other): <ins>        if other.is_subset(S.Reals):            # treat a subset of reals as a complex region            other = ComplexRegion.from_real(other)</ins>         if other.is_ComplexRegion:              # self in rectangular form


Question: elif self.polar and other.polar:                 return ComplexRegion(Union(self.sets, other.sets), polar=True)         if self == S.Complexes:            return self         return None  diff --git a/sympy/sets/sets.py b/sympy/sets/sets.py-- a/sympy/sets/sets.py++ b/sympy/sets/sets.py


Question: for a, b in zip(self.sets, other.sets))      def _union(self, other):<ins>        if other.is_subset(self):            return self</ins>         if not other.is_ProductSet:             return None         if len(other.args) != len(self.args):


Question: ('var', ['sup'], ['sub1', 'sub2'])      """<ins>    if len(text) == 0:        return text, [], []</ins>     pos = 0     name = None     supers = []

Exception when printing Symbol('') It has something to do with the unicode pretty printer. works.


Question: def __len__(self):         return Mul(*[len(s) for s in self.args]) <ins>    def __bool__(self):        return all([bool(s) for s in self.args])    __nonzero__ = __bool__</ins>  class Interval(Set, EvalfMixin):     """

set intersection gives TypeError: object of type 'Naturals0' has no len() This is from Optimistically marking this as easy to fix (I could be wrong).


Question: # don't change anything; this should already             # be a well formed mpf tuple             return mpf    rv = mpf_normalize(sign, man, expt, bc, prec, rnd)    # Necessary if mpmath is using the gmpy backend    from mpmath.libmp.backend import MPZ    rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)     return rv  # TODO: we should use the warnings module

lambdify precision loss with module=mpmath from high-precision Floats Floats with more than 16 digits are converted to double precision somewhere. Consider: Note has a 64-digit accurate Float in it (and the value is correct). But lambdifying and is not same: The help string for shows no loss: I haven't figured out how to look at the actual code yet, but somewhere something is being converted to double-precision (which might be fine for module=numpy but should not happen here).


Question: elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):<ins>            if prec == None:                prec = num.context.dps</ins>             num = num._mpf_          if prec is None:


Question: num[1] = long(num[1], 16)                 _mpf_ = tuple(num)             else:                if not num[1] and len(num) == 4:                if len(num) == 4:                     # handle normalization hack                     return Float._new(num, prec)                 else:                    _mpf_ = mpmath.mpf(                        S.NegativeOne**num[0]*num[1]*2**num[2])._mpf_                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)         elif isinstance(num, Float):             _mpf_ = num._mpf_             if prec < num._prec:                 _mpf_ = mpf_norm(_mpf_, prec)         else:            # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_          # special cases


Question: obj = Expr.__new__(cls)         obj._mpf_ = mpf_norm(_mpf_, _prec)        # XXX: Should this be obj._prec = obj._mpf_[3]?         obj._prec = _prec         return obj diff --git a/sympy/printing/lambdarepr.py b/sympy/printing/lambdarepr.py-- a/sympy/printing/lambdarepr.py++ b/sympy/printing/lambdarepr.py


Question: lstr = super(NumExprPrinter, self).doprint(expr)         return "evaluate('%s', truediv=True)" % lstr class MpmathPrinter(LambdaPrinter):    """    Lambda printer for mpmath which maintains precision for floats    """    def _print_Float(self, e):        # XXX: This does not handle setting mpmath.mp.dps. It is assumed that        # the caller of the lambdified function will have set it to sufficient        # precision to match the Floats in the expression.        # Remove 'mpz' if gmpy is installed.        args = str(tuple(map(int, e._mpf_)))        return 'mpf(%s)' % args def lambdarepr(expr, **settings):     """     Returns a string usable for lambdifying.diff --git a/sympy/solvers/solvers.py b/sympy/solvers/solvers.py-- a/sympy/solvers/solvers.py++ b/sympy/solvers/solvers.py


Question: # assume it's a sympy expression         if isinstance(f, Equality):             f = f.lhs - f.rhs        f = f.evalf()         syms = f.free_symbols         if fargs is None:             fargs = syms.copy().pop()diff --git a/sympy/utilities/decorator.py b/sympy/utilities/decorator.py-- a/sympy/utilities/decorator.py++ b/sympy/utilities/decorator.py


Question: import functools     import mpmath     def func_wrapper():    def func_wrapper(*args, **kwargs):         dps = mpmath.mp.dps         try:            func()            return func(*args, **kwargs)         finally:             mpmath.mp.dps = dps diff --git a/sympy/utilities/lambdify.py b/sympy/utilities/lambdify.py-- a/sympy/utilities/lambdify.py++ b/sympy/utilities/lambdify.py


Question: for term in syms:             namespace.update({str(term): term})     if _module_present('mpmath',namespaces) and printer is None:        #XXX: This has to be done here because of circular imports        from sympy.printing.lambdarepr import MpmathPrinter as printer     if _module_present('numpy',namespaces) and printer is None:         #XXX: This has to be done here because of circular imports         from sympy.printing.lambdarepr import NumPyPrinter as printerdiff --git a/sympy/utilities/runtests.py b/sympy/utilities/runtests.py-- a/sympy/utilities/runtests.py++ b/sympy/utilities/runtests.py


Question: clear_cache()             self._count += 1             random.seed(self._seed)            pytestfile = ""            if "XFAIL" in gl:                pytestfile = inspect.getsourcefile(gl["XFAIL"])            pytestfile2 = ""            if "slow" in gl:                pytestfile2 = inspect.getsourcefile(gl["slow"])             disabled = gl.get("disabled", False)             if not disabled:                 # we need to filter only those functions that begin with 'test_'                # that are defined in the testing file or in the file where                # is defined the XFAIL decorator                funcs = [gl[f] for f in gl.keys() if f.startswith("test_") and                    (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f])) and                    (inspect.getsourcefile(gl[f]) == filename or                     inspect.getsourcefile(gl[f]) == pytestfile or                     inspect.getsourcefile(gl[f]) == pytestfile2)]                # We have to be careful about decorated functions. As long as                # the decorator uses functools.wraps, we can detect it.                funcs = []                for f in gl:                    if (f.startswith("test_") and (inspect.isfunction(gl[f])                        or inspect.ismethod(gl[f]))):                        func = gl[f]                        # Handle multiple decorators                        while hasattr(func, '__wrapped__'):                            func = func.__wrapped__                        if inspect.getsourcefile(func) == filename:                            funcs.append(gl[f])                 if slow:                     funcs = [f for f in funcs if getattr(f, '_slow', False)]                 # Sorting of XFAILed functions isn't fixed yet :-(


Question: from sympy.sets.sets import FiniteSet from sympy.utilities.iterables import numbered_symbols from sympy.core.compatibility import range<ins>from sympy.core.relational import Nefrom sympy.functions.elementary.piecewise import Piecewise</ins>  ############################################################################### ########################## TRIGONOMETRIC FUNCTIONS ############################

simplifying exponential -trig identities Ideally, this would yield . Is there a way to do this? As a corollary, it would be awesome if could yield . Thank you for your consideration!


Question: def _eval_rewrite_as_sec(self, arg):         return 1 / sec(arg - S.Pi / 2, evaluate=False) <ins>    def _eval_rewrite_as_sinc(self, arg):        return arg*sinc(arg)</ins>     def _eval_conjugate(self):         return self.func(self.args[0].conjugate())


Question: return jn(0, arg)      def _eval_rewrite_as_sin(self, arg):        return sin(arg) / arg        return Piecewise((sin(arg)/arg, Ne(arg, 0)), (1, True))   ###############################################################################


Question: elif expr.is_Mul:             if not first and _coeff_isneg(expr):                 return True        if expr.is_Piecewise:            return True         if any([expr.has(x) for x in (Mod,)]):             return True         if (not last and            any([expr.has(x) for x in (Integral, Piecewise, Product, Sum)])):            any([expr.has(x) for x in (Integral, Product, Sum)])):             return True          return False

LaTeX printer inconsistent with pretty printer The LaTeX printer should always give the same output as the pretty printer, unless better output is possible from LaTeX. In some cases it is inconsistent. For instance: (I also don't think the assumptions should affect printing).


Question: >>> diop_solve(x + 3*y - 4*z + w - 6)     (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)     >>> diop_solve(x**2 + y**2 - 5)    {(-1, 2), (1, 2)}    {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}      See Also     ========

diophantine doesn't find solutions for 2x2+y2-16 Diophantine returns the empty set but and are solutions. I suspect there is some issue with the solving of the elliptic case, as for example also doesn't return all solutions: it returns and but fails to find and


Question: This method is generalised for many variables, below.      '''<del></del>     solutions = []     for i in range(len(B)):         tot_x, tot_y = [], []


Question: solns_pell = diop_DN(D, N)          if D < 0:            for solution in solns_pell:                s1 = P*Matrix([solution[0], solution[1]]) + Q                s2 = P*Matrix([-solution[0], solution[1]]) + Q                try:                    sol.add(tuple([as_int(_) for _ in s1]))                    sol.add(tuple([as_int(_) for _ in s2]))                except ValueError:                    pass            for x0, y0 in solns_pell:                for x in [-x0, x0]:                    for y in [-y0, y0]:                        s = P*Matrix([x, y]) + Q                        try:                            sol.add(tuple([as_int(_) for _ in s]))                        except ValueError:                            pass         else:             # In this case equation can be transformed into a Pell equation


Question: if sols:                     for x, y in sols:                         sol.append((d*x, d*y))                        if D == -1:                            sol.append((d*y, d*x))             return sol      elif D == 0:


Question: >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35     {(2, 3), (4, 1)}     >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25    {(3, 4)}    {(4, 3)}      References     ===========


Question: m1 = m1 // b             s, _exact = integer_nthroot(m1, 2)             if _exact:                if a == b and r > s:                if a == b and r < s:                     r, s = s, r                 sols.add((int(r), int(s)))


Question: func = getattr(mpmath, fname)         except (AttributeError, KeyError):             try:                return Float(self._imp_(*self.args), prec)                return Float(self._imp_(*[i.evalf(prec) for i in self.args]), prec)             except (AttributeError, TypeError, ValueError):                 return

evalf does not call imp recursively Example from The code for this is in . It isn't calling evalf recursively on the return of .


Question: else:                 return Derivative(self, self.args[argindex - 1], evaluate=False)         # See issue 4624 and issue 4719 and issue 5600        arg_dummy = Dummy('xi_%i' % argindex)        arg_dummy.dummy_index = hash(self.args[argindex - 1])        arg_dummy = Dummy('xi_%i' % argindex, dummy_index=hash(self.args[argindex - 1]))         new_args = [arg for arg in self.args]         new_args[argindex-1] = arg_dummy         return Subs(Derivative(self.func(*new_args), arg_dummy),

Dummy fails when is re-evaluated in S and srepr Hi all! Well, i found this little problem, Dummy is a nice function but in the way is implemented exist this: Basically, if you works with Dummy, and you get the expression with srepr or similar, when you eval it every Dummy will be interpreted as a new Dummy, so it fails, in the example you can see we can't eval the second expression because the 2 Dummy expression are interpreted as differents, other ex: So thinking a solution can be use a hash or similar function, like: Always will exist the hash collision, but at least to cover all possible can be sympy check the existents Dummy expressions and check the hash never by equal to other, the probability of the hash collision, to be equal, in the same context, with the same name, and in the same expression, i think is very low. Maybe instead use a hash can be a random expression, with chars like , that can help to avoid hash collision. Thx. Cya.


Question: obj = None             else:                 if not is_symbol:                    new_v = Dummy('xi_%i' % i)                    new_v.dummy_index = hash(v)                    new_v = Dummy('xi_%i' % i, dummy_index=hash(v))                     expr = expr.xreplace({v: new_v})                     old_v = v                     v = new_vdiff --git a/sympy/core/symbol.py b/sympy/core/symbol.py-- a/sympy/core/symbol.py++ b/sympy/core/symbol.py


Question: import string import re as _re<ins>import random</ins>   class Symbol(AtomicExpr, Boolean):


Question: class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy     >>> bool(Dummy("x") == Dummy("x")) == True     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.


Question: """     # In the rare event that a Dummy object needs to be recreated, both the    # `name` and `dummy_index` should be passed.  This is used by `srepr` for    # example:    # >>> d1 = Dummy()    # >>> d2 = eval(srepr(d1))    # >>> d2 == d1    # True    #    # If a new session is started between `srepr` and `eval`, there is a very    # small chance that `d2` will be equal to a previously-created Dummy.     _count = 0    _dummyorder = {}    _prng = random.Random()      __slots__ = ['dummy_index']      is_Dummy = True     def __new__(cls, name=None, **assumptions):    def __new__(cls, name=None, dummy_index=None, **assumptions):        if dummy_index is not None:            assert name is not None, "If you specify a dummy_index, you must also provide a name"         if name is None:             name = "Dummy_" + str(Dummy._count)          cls._sanitize(assumptions, cls)         obj = Symbol.__xnew__(cls, name, **assumptions)         while dummy_index is None:            # The dummy_index that *we* generate will be a smallish positive            # integers (at least Codeprinter assumes this).  But we do not            # impose this if dummy_index was passed in.            dummy_index = Dummy._prng.randint(10**6, 10**7-1)            if dummy_index in Dummy._dummyorder:                dummy_index = None        # Store count but don't update it if we already made this Dummy        Dummy._dummyorder.setdefault(dummy_index, Dummy._count)        obj.dummy_index = dummy_index         Dummy._count += 1        obj.dummy_index = Dummy._count         return obj      def __getstate__(self):


Question: @cacheit     def sort_key(self, order=None):        # some tests depend on order of creation of Dummys         return self.class_key(), (            2, (str(self), self.dummy_index)), S.One.sort_key(), S.One            2, (str(self), Dummy._dummyorder[self.dummy_index])), S.One.sort_key(), S.One      def _hashable_content(self):         return Symbol._hashable_content(self) + (self.dummy_index,)diff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


Question: def _print_Symbol(self, expr):         d = expr._assumptions.generator<ins>        # print the dummy_index like it was an assumption        if expr.is_Dummy:            d['dummy_index'] = expr.dummy_index</ins>         if d == {}:             return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))         else:


Question: def _print_Sum(self, expr):         return "Hold[Sum[" + ', '.join(self.doprint(a) for a in expr.args) + "]]" <ins>    def _print_Derivative(self, expr):        return "Hold[D[" + ', '.join(self.doprint(a) for a in expr.args) + "]]"</ins>  def mathematica_code(expr, **settings):     r"""Converts an expr to a string of the Wolfram Mathematica code

matematica code printer does not handle floats and derivatives correctly In its current state the mathematica code printer does not handle Derivative(func(vars), deriver) e.g. Derivative(f(t), t) yields Derivative(f(t), t) instead of D[f[t],t] Also floats with exponents are not handled correctly e.g. 1.0e-4 is not converted to 1.0^-4 This has an easy fix by adding the following lines to MCodePrinter: def printDerivative(self, expr): return "D[%s]" % (self.stringify(, ", ")) def printFloat(self, expr): res =str(expr) return res.replace('e','^')


Question: args = flatten(args)          if len(args) == 0:            return S.EmptySet            return S.UniversalSet          # args can't be ordered for Partition see issue #9608         if 'Partition' not in [type(a).__name__ for a in args]:

Empty intersection should be UniversalSet It should be . See (settheory)#Nullary_intersection


Question: def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a positive integer ``n``, ``factorint(n)`` returns a dict containing     the prime factors of ``n`` as keys and their respective multiplicities

List of prime factors including multiplicity is missing The vast majority of the time when using prime factorization in algorithms I'm interested in a list of prime factors. E.g. for 24 it's . However sympy (to my knowledge) only provides which returns a dictionary. I always end up writing a helper function: factorlist = lambda fac: sum(([p] * fac[p] for p in sorted(fac)), []) It would be really nice if factorizations in this format were directly provided by sympy, either by an option to (e.g. ) or under a new function name entirely.


Question: >>> factorint(3*101**7, limit=5)     {3: 1, 101: 7} <ins>    List of Factors:    If ``multiple`` is set to ``True`` then a list containing the    prime factors including multiplicities is returned.    >>> factorint(24, multiple=True)    [2, 2, 2, 3]</ins>     Visual Factorization:      If ``visual`` is set to ``True``, then it will return a visual


Question: smoothness, smoothness_p, divisors      """<ins>    if multiple:        fac = factorint(n, limit=limit, use_trial=use_trial,                           use_rho=use_rho, use_pm1=use_pm1,                           verbose=verbose, visual=False, multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p in sorted(fac)), [])        return factorlist</ins>     factordict = {}     if visual and not isinstance(n, Mul) and not isinstance(n, dict):         factordict = factorint(n, limit=limit, use_trial=use_trial,


Question: def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,              verbose=False, visual=None):              verbose=False, visual=None, multiple=False):     r"""     Given a Rational ``r``, ``factorrat(r)`` returns a dict containing     the prime factors of ``r`` as keys and their respective multiplicities


Question: - ``use_rho``: Toggle use of Pollard's rho method         - ``use_pm1``: Toggle use of Pollard's p-1 method         - ``verbose``: Toggle detailed printing of progress        - ``multiple``: Toggle returning a list of factors or dict         - ``visual``: Toggle product form of output     """     from collections import defaultdict    if multiple:        fac = factorrat(rat, limit=limit, use_trial=use_trial,                  use_rho=use_rho, use_pm1=use_pm1,                  verbose=verbose, visual=False,multiple=False)        factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S(1)/p]*(-1*fac[p])                               for p, _ in sorted(fac.items(),                                                        key=lambda elem: elem[0]                                                        if elem[1] > 0                                                        else 1/elem[0])), [])        return factorlist     f = factorint(rat.p, limit=limit, use_trial=use_trial,                   use_rho=use_rho, use_pm1=use_pm1,                   verbose=verbose).copy()


Question: new_args = []         n_intervals = len(b1.args)         if n_intervals != len(b2.args):            raise ValueError("Args of b1 and b2 are not equal")        new_args.append((c*b1.args[0].expr, b1.args[0].cond))        for i in range(1, n_intervals - 1):            new_args.append((                c*b1.args[i].expr + d*b2.args[i - 1].expr,                b1.args[i].cond            ))        new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))        new_args.append(b2.args[-1])            # Args of b1 and b2 are not equal. Just combining the Piecewise without any fancy optimisation            p1 = piecewise_fold(c*b1)            p2 = piecewise_fold(d*b2)            # Search all Piecewise arguments except (0, True)            p2args = list(p2.args[:-1])            # This merging algorithm assume the conditions in p1 and p2 are sorted            for arg in p1.args[:-1]:                # Conditional of Piecewise are And objects                # the args of the And object is a tuple of two Relational objects                # the numerical value is in the .rhs of the Relational object                expr = arg.expr                cond = arg.cond                lower = cond.args[0].rhs                # Check p2 for matching conditions that can be merged                for i, arg2 in enumerate(p2args):                    expr2 = arg2.expr                    cond2 = arg2.cond                    lower_2 = cond2.args[0].rhs                    upper_2 = cond2.args[1].rhs                    if cond2 == cond:                        # Conditions match, join expressions                        expr += expr2                        # Remove matching element                        del p2args[i]                        # No need to check the rest                        break                    elif lower_2 < lower and upper_2 <= lower:                        # Check if arg2 condition smaller than arg1, add to new_args by itself (no match expected in p1)                        new_args.append(arg2)                        del p2args[i]                        break                # Checked all, add expr and cond                new_args.append((expr, cond))            # Add remaining items from p2args            new_args.extend(p2args)            # Add final (0, True)            new_args.append((0, True))        else:            new_args.append((c*b1.args[0].expr, b1.args[0].cond))            for i in range(1, n_intervals - 1):                new_args.append((                    c*b1.args[i].expr + d*b2.args[i - 1].expr,                    b1.args[i].cond                ))            new_args.append((d*b2.args[-2].expr, b2.args[-2].cond))            new_args.append(b2.args[-1])         rv = Piecewise(*new_args)      return rv.expand()  def bspline_basis(d, knots, n, x, close=True):def bspline_basis(d, knots, n, x):     """The `n`-th B-spline at `x` of degree `d` with knots.      B-Splines are piecewise polynomials of degree `d` [1]_.  They are defined on

b splines of degree 1? Looking at the spline_basis function: This seems to break while the following is fine: I can tweak in extra knots, i.e. placing them at (0.1,0.2, 10.1,10.2 in the example) but this is still not really giving the desired basis matrix. Or am I just missing something very obvious? I always generated knots for bspline basis matrix by taking the list of knots and:


Question: Here is an example of a cubic B-spline:          >>> bspline_basis(3, range(5), 0, x)        Piecewise((x**3/6, (x >= 0) & (x < 1)),        Piecewise((x**3/6, (x >= 0) & (x <= 1)),                   (-x**3/2 + 2*x**2 - 2*x + 2/3,                  (x >= 1) & (x < 2)),                  (x >= 1) & (x <= 2)),                   (x**3/2 - 4*x**2 + 10*x - 22/3,                  (x >= 2) & (x < 3)),                  (x >= 2) & (x <= 3)),                   (-x**3/6 + 2*x**2 - 8*x + 32/3,                   (x >= 3) & (x <= 4)),                   (0, True))


Question: raise ValueError('n + d + 1 must not exceed len(knots) - 1')     if d == 0:         result = Piecewise(            (S.One, Interval(knots[n], knots[n + 1], False,             not close).contains(x)),            (S.One, Interval(knots[n], knots[n + 1]).contains(x)),             (0, True)         )     elif d > 0:         denom = knots[n + d + 1] - knots[n + 1]         if denom != S.Zero:             B = (knots[n + d + 1] - x)/denom            b2 = bspline_basis(d - 1, knots, n + 1, x, close)            b2 = bspline_basis(d - 1, knots, n + 1, x)         else:             b2 = B = S.Zero          denom = knots[n + d] - knots[n]         if denom != S.Zero:             A = (x - knots[n])/denom            b1 = bspline_basis(                d - 1, knots, n, x, close and (B == S.Zero or b2 == S.Zero))            b1 = bspline_basis(d - 1, knots, n, x)         else:             b1 = A = S.Zero


Question: >>> knots = range(5)     >>> splines = bspline_basis_set(d, knots, x)     >>> splines    [Piecewise((x**2/2, (x >= 0) & (x < 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x < 2)),    [Piecewise((x**2/2, (x >= 0) & (x <= 1)),               (-x**2 + 3*x - 3/2, (x >= 1) & (x <= 2)),                (x**2/2 - 3*x + 9/2, (x >= 2) & (x <= 3)),                (0, True)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x < 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x < 3)),    Piecewise((x**2/2 - x + 1/2, (x >= 1) & (x <= 2)),              (-x**2 + 5*x - 11/2, (x >= 2) & (x <= 3)),               (x**2/2 - 4*x + 8, (x >= 3) & (x <= 4)),               (0, True))]


Question: import decimal import fractions import math<ins>import warnings</ins> import re as regex from collections import defaultdict

Float constructor should allow to set binary precision I discussed this in some other issues, but I don't think I've opened an issue for it. The Float constructor only allows you to set the decimal precision. It then converts this to binary precision and saves that in . The problem here is that there are fewer decimal precisions than binary precisions. For example: So for instance, if you had a float that used 54 binary digits, it would be difficult to create a Float from it. I'm not even sure if it's possible, since in the current constructor, the argument overrides the fourth argument of a tuple input. One issue here is that everywhere else in the Sympy and mpmath code, refers to binary precision and refers to decimal precision. But currently, the second argument to is called , but refers to the decimal precision. So ideally, it should be where would override the default value of , and calling both (even consistently), like would be an error. Since the keyword argument name has to change, it would be a backwards compatibility break for anyone who calls Float like . Ideally this would require a deprecation cycle, but it's not possible to detect if someone is calling meaning the old way (20 decimal digits) or the new way (20 binary digits). The good news is that and call this argument , so there's no need to change things there.


Question: from sympy.utilities.misc import debug, filldedent from .evaluate import global_evaluate <ins>from sympy.utilities.exceptions import SymPyDeprecationWarning</ins> rnd = mlib.round_nearest  _LOG2 = math.log(2)


Question: is_Float = True     def __new__(cls, num, prec=None):    def __new__(cls, num, dps=None, prec=None, precision=None):        if prec is not None:            SymPyDeprecationWarning(                            feature="Using 'prec=XX' to denote decimal precision",                            useinstead="'dps=XX' to denote decimal and 'precision=XX' "\                                              "for binary precision",                            value="This is an effort to improve functionality "\                                       "of Float class. ").warn()            dps = prec        if dps is not None and precision is not None:            raise ValueError('Both decimal and binary precision supplied. '                             'Supply only one. ')         if isinstance(num, string_types):             num = num.replace(' ', '')             if num.startswith('.') and len(num) > 1:


Question: elif num is S.NegativeInfinity:             num = '-inf'         elif isinstance(num, mpmath.mpf):            if prec == None:                prec = num.context.dps            if precision is None:                if dps is None:                    precision = num.context.prec             num = num._mpf_         if prec is None:        if dps is None and precision is None:             dps = 15             if isinstance(num, Float):                 return num


Question: if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                     dps = max(15, dps)        elif prec == '':                    precision = mlib.libmpf.dps_to_prec(dps)        elif precision == '' and dps is None or precision is None and dps == '':             if not isinstance(num, string_types):                 raise ValueError('The null string can only be used when '                 'the number to Float is passed as a string or an integer.')


Question: num, dps = _decimal_to_Rational_prec(Num)                     if num.is_Integer and isint:                         dps = max(dps, len(str(num).lstrip('-')))                        precision = mlib.libmpf.dps_to_prec(dps)                     ok = True             if ok is None:                 raise ValueError('string-float not recognized: %s' % num)        else:            dps = prec         prec = mlib.libmpf.dps_to_prec(dps)        # decimal precision(dps) is set and maybe binary precision(precision)        # as well.From here on binary precision is used to compute the Float.        # Hence, if supplied use binary precision else translate from decimal        # precision.        if precision is None or precision == '':            precision = mlib.libmpf.dps_to_prec(dps)         if isinstance(num, float):            _mpf_ = mlib.from_float(num, prec, rnd)            _mpf_ = mlib.from_float(num, precision, rnd)         elif isinstance(num, string_types):            _mpf_ = mlib.from_str(num, prec, rnd)            _mpf_ = mlib.from_str(num, precision, rnd)         elif isinstance(num, decimal.Decimal):             if num.is_finite():                _mpf_ = mlib.from_str(str(num), prec, rnd)                _mpf_ = mlib.from_str(str(num), precision, rnd)             elif num.is_nan():                 _mpf_ = _mpf_nan             elif num.is_infinite():


Question: else:                 raise ValueError("unexpected decimal value %s" % str(num))         elif isinstance(num, Rational):            _mpf_ = mlib.from_rational(num.p, num.q, prec, rnd)            _mpf_ = mlib.from_rational(num.p, num.q, precision, rnd)         elif isinstance(num, tuple) and len(num) in (3, 4):             if type(num[1]) is str:                 # it's a hexadecimal (coming from a pickled object)


Question: else:                 if len(num) == 4:                     # handle normalization hack                    return Float._new(num, prec)                    return Float._new(num, precision)                 else:                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(prec)                    return (S.NegativeOne**num[0]*num[1]*S(2)**num[2]).evalf(precision)         elif isinstance(num, Float):             _mpf_ = num._mpf_            if prec < num._prec:                _mpf_ = mpf_norm(_mpf_, prec)            if precision < num._prec:                _mpf_ = mpf_norm(_mpf_, precision)         else:             # XXX: We lose precision here.             _mpf_ = mpmath.mpf(num)._mpf_


Question: obj = Expr.__new__(cls)         obj._mpf_ = _mpf_        obj._prec = prec        obj._prec = precision         return obj      @classmethoddiff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


Question: return 'Fraction(%s, %s)' % (self._print(expr.numerator), self._print(expr.denominator))      def _print_Float(self, expr):        dps = prec_to_dps(expr._prec)         r = mlib.to_str(expr._mpf_, repr_dps(expr._prec))        return "%s('%s', prec=%i)" % (expr.__class__.__name__, r, dps)        return "%s('%s', precision=%i)" % (expr.__class__.__name__, r, expr._prec)      def _print_Sum2(self, expr):         return "Sum2(%s, (%s, %s, %s))" % (self._print(expr.f), self._print(expr.i),


Question: from collections import defaultdict <del></del> class Expr(Basic, EvalfMixin):     """     Base class for algebraic expressions.

cannot extract_multiplicatively(-2) from (-2x - 2y) I think this might be a bug. similarly: Assuming it is indeed a bug, here is why it happens: Look in where: which is then made into a non-evaluated , from which cannot be multiplicatively extracted; for example: do you think this is bug? (see your commit : not clear whether we still need this special case anyway)


Question: x/6          """<ins>        from .function import _coeff_isneg</ins>         c = sympify(c)         if self is S.NaN:             return None


Question: return self         elif c == self:             return S.One         if c.is_Add:             cc, pc = c.primitive()             if cc is not S.One:                 c = Mul(cc, pc, evaluate=False)         if c.is_Mul:             a, b = c.as_two_terms()             x = self.extract_multiplicatively(a)             if x is not None:                 return x.extract_multiplicatively(b)         quotient = self / c         if self.is_Number:             if self is S.Infinity:


Question: return quotient         elif self.is_Add:             cs, ps = self.primitive()            if cs is not S.One:                return Mul(cs, ps, evaluate=False).extract_multiplicatively(c)            # assert cs >= 1            if c.is_Number and c is not S.NegativeOne:                # assert c != 1 (handled at top)                if cs is not S.One:                    if c.is_negative:                        xc = -(cs.extract_multiplicatively(-c))                    else:                        xc = cs.extract_multiplicatively(c)                    if xc is not None:                        return xc*ps  # rely on 2-arg Mul to restore Add                return  # |c| != 1 can only be extracted from cs            if c == ps:                return cs            # check args of ps             newargs = []            for arg in self.args:            for arg in ps.args:                 newarg = arg.extract_multiplicatively(c)                if newarg is not None:                    newargs.append(newarg)                else:                    return None            return Add(*newargs)                if newarg is None:                    return  # all or nothing                newargs.append(newarg)            # args should be in same order so use unevaluated return            if cs is not S.One:                return Add._from_args([cs*t for t in newargs])            else:                return Add._from_args(newargs)         elif self.is_Mul:             args = list(self.args)             for i, arg in enumerate(args):


Question: else:                 return Derivative(self, self.args[argindex - 1], evaluate=False)         # See issue 4624 and issue 4719 and issue 5600        arg_dummy = Dummy('xi_%i' % argindex)        arg_dummy.dummy_index = hash(self.args[argindex - 1])        arg_dummy = Dummy('xi_%i' % argindex, dummy_index=hash(self.args[argindex - 1]))         new_args = [arg for arg in self.args]         new_args[argindex-1] = arg_dummy         return Subs(Derivative(self.func(*new_args), arg_dummy),


Question: obj = None             else:                 if not is_symbol:                    new_v = Dummy('xi_%i' % i)                    new_v.dummy_index = hash(v)                    new_v = Dummy('xi_%i' % i, dummy_index=hash(v))                     expr = expr.xreplace({v: new_v})                     old_v = v                     v = new_vdiff --git a/sympy/core/symbol.py b/sympy/core/symbol.py-- a/sympy/core/symbol.py++ b/sympy/core/symbol.py


Question: import string import re as _re<ins>import random</ins>   class Symbol(AtomicExpr, Boolean):


Question: class Dummy(Symbol):    """Dummy symbols are each unique, identified by an internal count index:    """Dummy symbols are each unique, even if they have the same name:      >>> from sympy import Dummy    >>> bool(Dummy("x") == Dummy("x")) == True    >>> Dummy("x") == Dummy("x")     False     If a name is not supplied then a string value of the count index will be    If a name is not supplied then a string value of an internal count will be     used. This is useful when a temporary variable is needed and the name     of the variable used in the expression is not important.


Question: """     # In the rare event that a Dummy object needs to be recreated, both the    # `name` and `dummy_index` should be passed.  This is used by `srepr` for    # example:    # >>> d1 = Dummy()    # >>> d2 = eval(srepr(d1))    # >>> d2 == d1    # True    #    # If a new session is started between `srepr` and `eval`, there is a very    # small chance that `d2` will be equal to a previously-created Dummy.     _count = 0    _prng = random.Random()    _base_dummy_index = _prng.randint(10**6, 9*10**6)      __slots__ = ['dummy_index']      is_Dummy = True     def __new__(cls, name=None, **assumptions):    def __new__(cls, name=None, dummy_index=None, **assumptions):        if dummy_index is not None:            assert name is not None, "If you specify a dummy_index, you must also provide a name"         if name is None:             name = "Dummy_" + str(Dummy._count)         if dummy_index is None:            dummy_index = Dummy._base_dummy_index + Dummy._count            Dummy._count += 1         cls._sanitize(assumptions, cls)         obj = Symbol.__xnew__(cls, name, **assumptions)         Dummy._count += 1        obj.dummy_index = Dummy._count        obj.dummy_index = dummy_index         return obj      def __getstate__(self):diff --git a/sympy/printing/repr.py b/sympy/printing/repr.py-- a/sympy/printing/repr.py++ b/sympy/printing/repr.py


Question: def _print_Symbol(self, expr):         d = expr._assumptions.generator<ins>        # print the dummy_index like it was an assumption        if expr.is_Dummy:            d['dummy_index'] = expr.dummy_index</ins>         if d == {}:             return "%s(%s)" % (expr.__class__.__name__, self._print(expr.name))         else:


Question: # remove it             if Func is Add:                 take = min(func_dicts[k][i] for i in com_dict)                com_func_take = Mul(take, from_dict(com_dict), evaluate=False)                _sum = from_dict(com_dict)                if take == 1:                    com_func_take = _sum                else:                    com_func_take = Mul(take, _sum, evaluate=False)             else:                 take = igcd(*[func_dicts[k][i] for i in com_dict])                com_func_take = Pow(from_dict(com_dict), take, evaluate=False)                base = from_dict(com_dict)                if take == 1:                    com_func_take = base                else:                    com_func_take = Pow(base, take, evaluate=False)             for di in com_dict:                 func_dicts[k][di] -= take*com_dict[di]             # compute the remaining expression

Test failure in Travis I was able to reproduce this locally on a 64-bit system running Ubuntu 16.04. How to reproduce:


Question: #     R = [(x0, d + f), (x1, b + d)]     #     C = [e + x0 + x1, g + x0 + x1, a + c + d + f + g]     # but the args of C[-1] should not be `(a + c, d + f + g)`    nested = [[i for i in f.args if isinstance(i, f.func)] for f in exprs]     for i in range(len(exprs)):         F = reduced_exprs[i].func         if not (F is Mul or F is Add):             continue        nested = [a for a in exprs[i].args if isinstance(a, F)]        args = []        for a in reduced_exprs[i].args:            if isinstance(a, F):                for ai in a.args:                    if isinstance(ai, F) and ai not in nested:                        args.extend(ai.args)                    else:                        args.append(ai)            else:                args.append(a)        reduced_exprs[i] = F(*args)        if any(isinstance(a, F) for a in reduced_exprs[i].args):            reduced_exprs[i] = F(*reduced_exprs[i].args)      return replacements, reduced_exprs


Question: def _get_comment(self, text):         return "! {0}".format(text)<ins>#issue 12267    def _print_sign(self,func):        if func.args[0].is_integer:            return "merge(0, isign(1, {0}), {0} == 0)".format(self._print(func.args[0]))        elif func.args[0].is_complex:            return "merge(cmplx(0d0, 0d0), {0}/abs({0}), abs({0}) == 0d0)".format(self._print(func.args[0]))        else:            return "merge(0d0, dsign(1d0, {0}), {0} == 0d0)".format(self._print(func.args[0]))</ins>      def _declare_number_const(self, name, value):         return "parameter ({0} = {1})".format(name, value)

Codegen: sign function in Fortran The Fortran code generated by Sympy for the sign function is not a valid Fortran syntax. With Sympy 1.0 and Python 3.6: (The same behavior is obtained with .) The syntax of the sign function in Fortran is given . I guess it would be preferable to generate something like or depending of the context. I'm not sure how to get the same behavior than Sympy for , but at least it would be compilable.


Question: from functools import wraps from sympy.core import S, Symbol, Tuple, Integer, Basic, Exprfrom sympy.core import S, Symbol, Tuple, Integer, Basic, Expr, Eq from sympy.core.decorators import call_highest_priority from sympy.core.compatibility import range from sympy.core.sympify import SympifyError, sympify from sympy.functions import conjugate, adjointfrom sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices import ShapeError from sympy.simplify import simplify

Sum of the elements of an identity matrix is zero I think this is a bug. I created a matrix by M.T * M under an assumption that M is orthogonal. SymPy successfully recognized that the result is an identity matrix. I tested its identity-ness by element-wise, queries, and sum of the diagonal elements and received expected results. However, when I attempt to evaluate the total sum of the elements the result was 0 while 'n' is expected.


Question: if self.args[0] != v.args[0]:             return S.Zero <del>        from sympy import KroneckerDelta</del>         return KroneckerDelta(self.args[1], v.args[1])*KroneckerDelta(self.args[2], v.args[2])


Question: return self      def _entry(self, i, j):        if i == j:        eq = Eq(i, j)        if eq is S.true:             return S.One        else:        elif eq is S.false:             return S.Zero        return KroneckerDelta(i, j)      def _eval_determinant(self):         return S.One


Question: from __future__ import print_function, division  from sympy.matrices.expressions import MatrixExprfrom sympy.core import Sfrom sympy.core import S, Eqfrom sympy.functions.special.tensor_functions import KroneckerDelta class DiagonalMatrix(MatrixExpr):     arg = property(lambda self: self.args[0])     shape = property(lambda self: (self.arg.shape[0], self.arg.shape[0]))      def _entry(self, i, j):        return S.Zero if i != j else self.arg[i, 0]        eq = Eq(i, j)        if eq is S.false:            return S.Zero        elif eq is S.true:            return self.arg[i, i]        return self.arg[i, j]*KroneckerDelta(i, j)  class DiagonalOf(MatrixExpr):     arg = property(lambda self: self.args[0])

DiagonalMatrix[i, j] -0 Similar to , DiagonalMatrix references to position (i,j) give 0:


Question: def _eval_is_upper_hessenberg(self):         return all(self[i, j].is_zero                    for i in range(2, self.rows)                   for j in range(i - 1))                   for j in range(min(self.cols, (i - 1))))      def _eval_values(self):         return [i for i in self if not i.is_zero]

isupper() raises IndexError for tall matrices The function Matrix.isupper raises an IndexError for a 4x2 matrix of zeros. The code for isupper() is For a 4x2 matrix, isupper iterates over the indices: The attempt to index the (3,2) entry appears to be the source of the error.


Question: """         return all(self[i, j].is_zero                    for i in range(1, self.rows)                   for j in range(i))                   for j in range(min(i, self.cols)))      @property     def is_zero(self):


Question: # counting starts from 1.          temp = flatten(args)        if has_dups(temp):            if is_cycle:                raise ValueError('there were repeated elements; to resolve '                'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args]))            else:                raise ValueError('there were repeated elements.')        if has_dups(temp) and not is_cycle:            raise ValueError('there were repeated elements.')         temp = set(temp)          if not is_cycle and \

constructor fails with non-disjoint cycles Calling raises a instead of constructing the identity permutation. If the cycles passed in are non-disjoint, they should be applied in left-to-right order and the resulting permutation should be returned. This should be easy to compute. I don't see a reason why non-disjoint cycles should be forbidden.


Question: from sympy.core.compatibility import as_int, SYMPY_INTS, range from sympy.core.singleton import S from sympy.core.function import Function<ins>from sympy.core.expr import Expr</ins>  small_trailing = [i and max(int(not i % 2**j) and j for j in range(1, 8))     for i in range(256)]

Totient of any non-integer number According to the Totient function definition on , the totient of non-integer numbers is not there. But in sympy: the value is returned, instead of an error.


Question: for p, k in factors.items():                 t *= (p - 1) * p**(k - 1)             return t<ins>        elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False):            raise ValueError("n must be a positive integer")</ins>      def _eval_is_integer(self):         return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])


Question: from sympy.core.compatibility import reduce from sympy.combinatorics import Permutation <ins></ins> # TODO you are a bit excessive in the use of Dummies # TODO dummy point, literal field # TODO too often one needs to call doit or simplify on the output, check the

diffgeom does not support multivector fields (0,m) well enough A limitation of the diffgeom package is that it does not provide support for fields higher than (0,m). TensorProduct, WedgeProduct, and others all assume inputs of differential form-fields, while mixed multivector fields make sense in some contexts (such as Poisson geometry). I'll work on implementing (n,m)-fields in the current code, where it makes sense.


Question: if covariant_order(scalar_field) or contravariant_order(scalar_field):             raise ValueError('Only scalar fields can be supplied as arguments to vector fields.') <ins>        if scalar_field is None:            return self</ins>         base_scalars = list(scalar_field.atoms(BaseScalarField))          # First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)


Question: """Tensor product of forms.      The tensor product permits the creation of multilinear functionals (i.e.    higher order tensors) out of lower order forms (e.g. 1-forms). However, the    higher tensors thus created lack the interesting features provided by the    other type of product, the wedge product, namely they are not antisymmetric    and hence are not form fields.    higher order tensors) out of lower order fields (e.g. 1-forms and vector    fields). However, the higher tensors thus created lack the interesting    features provided by the other type of product, the wedge product, namely    they are not antisymmetric and hence are not form fields.      Examples     ========


Question: 0     >>> TensorProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)     x**2<ins>    >>> TensorProduct(R2.e_x, R2.e_y)(R2.x**2, R2.y**2)    4*x*y    >>> TensorProduct(R2.e_y, R2.dx)(R2.y)    dx</ins>      You can nest tensor products.


Question: """     def __new__(cls, *args):        if any(contravariant_order(a) for a in args):            raise ValueError('A vector field was supplied as an argument to TensorProduct.')        scalar = Mul(*[m for m in args if covariant_order(m) == 0])        forms = [m for m in args if covariant_order(m)]        if forms:            if len(forms) == 1:                return scalar*forms[0]            return scalar*super(TensorProduct, cls).__new__(cls, *forms)        scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])        multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]        if multifields:            if len(multifields) == 1:                return scalar*multifields[0]            return scalar*super(TensorProduct, cls).__new__(cls, *multifields)         else:             return scalar


Question: super(TensorProduct, self).__init__()         self._args = args     def __call__(self, *v_fields):        """Apply on a list of vector_fields.    def __call__(self, *fields):        """Apply on a list of fields.         If the number of vector fields supplied is not equal to the order of        the form field the list of arguments is padded with ``None``'s.        If the number of input fields supplied is not equal to the order of        the tensor product field, the list of arguments is padded with ``None``'s.          The list of arguments is divided in sublists depending on the order of         the forms inside the tensor product. The sublists are provided as         arguments to these forms and the resulting expressions are given to the         constructor of ``TensorProduct``.         """        tot_order = covariant_order(self)        tot_args = len(v_fields)        tot_order = covariant_order(self) + contravariant_order(self)        tot_args = len(fields)         if tot_args != tot_order:            v_fields = list(v_fields) + [None]*(tot_order - tot_args)        orders = [covariant_order(f) for f in self._args]            fields = list(fields) + [None]*(tot_order - tot_args)        orders = [covariant_order(f) + contravariant_order(f) for f in self._args]         indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]        v_fields = [v_fields[i:j] for i, j in zip([0] + indices, indices + [None])]        multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, v_fields)]        fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]        multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]         return TensorProduct(*multipliers)      def _latex(self, printer, *args):


Question: -1     >>> WedgeProduct(R2.dx, R2.x*R2.dy)(R2.x*R2.e_x, R2.e_y)     x**2<ins>    >>> WedgeProduct(R2.e_x,R2.e_y)(R2.y,None)    -e_x</ins>      You can nest wedge products.


Question: """     # TODO the calculation of signatures is slow     # TODO you do not need all these permutations (neither the prefactor)    def __call__(self, *vector_fields):    def __call__(self, *fields):         """Apply on a list of vector_fields.          The expression is rewritten internally in terms of tensor products and evaluated."""        orders = (covariant_order(e) for e in self.args)        orders = (covariant_order(e) + contravariant_order(e) for e in self.args)         mul = 1/Mul(*(factorial(o) for o in orders))        perms = permutations(vector_fields)        perms = permutations(fields)         perms_par = (Permutation(            p).signature() for p in permutations(list(range(len(vector_fields)))))            p).signature() for p in permutations(list(range(len(fields)))))         tensor_prod = TensorProduct(*self.args)         return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])


Question: return 0     elif isinstance(expr, BaseVectorField):         return 1<ins>    elif isinstance(expr, TensorProduct):        return sum(contravariant_order(a) for a in expr.args)</ins>     elif not _strict or expr.atoms(BaseScalarField):         return 0     else:  # If it does not contain anything related to the diffgeom module and it is _strict


Question: ========          >>> from sympy import Poly        >>> from sympy.abc import x, y        >>> from sympy.abc import x, y, z          >>> Poly(x**2 + 1).free_symbols         {x}

Poly(x,x,y).free_symbols -{x, y} instead of just {x} No free symbols of generators that don't appear in the expression of the polynomial should appear in the set of free symbols.


Question: {x, y}         >>> Poly(x**2 + y, x).free_symbols         {x, y}        >>> Poly(x**2 + y, x, z).free_symbols        {x, y}          """        symbols = set([])        for gen in self.gens:            symbols |= gen.free_symbols        symbols = set()        gens = self.gens        for i in range(len(gens)):            for monom in self.monoms():                if monom[i]:                    symbols |= gens[i].free_symbols                    break          return symbols | self.free_symbols_in_domain


Question: def ltrim(f, gen):         """        Remove dummy generators from the "left" of ``f``.        Remove dummy generators from ``f`` that are to the left of        specified ``gen`` in the generators as ordered. When ``gen``        is an integer, it refers to the generator located at that        position within the tuple of generators of ``f``.          Examples         ========


Question: >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)         Poly(y**2 + y*z**2, y, z, domain='ZZ')        >>> Poly(z, x, y, z).ltrim(-1)        Poly(z, z, domain='ZZ')          """         rep = f.as_dict(native=True)         j = f._gen_to_level(gen)         terms = {}          for monom, coeff in rep.items():            monom = monom[j:]             if monom not in terms:                terms[monom] = coeff            else:            if any(i for i in monom[:j]):                # some generator is used in the portion to be trimmed                 raise PolynomialError("can't left trim %s" % f)             terms[monom[j:]] = coeff         gens = f.gens[j:]          return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens)


Question: False          """        indices = set([])        indices = set()          for gen in gens:             try:diff --git a/sympy/solvers/polysys.py b/sympy/solvers/polysys.py-- a/sympy/solvers/polysys.py++ b/sympy/solvers/polysys.py


Question: from sympy.polys import Poly, groebner, roots from sympy.polys.polytools import parallel_poly_from_expr from sympy.polys.polyerrors import (ComputationFailed,    PolificationFailed, CoercionFailed)    PolificationFailed, CoercionFailed, PolynomialError) from sympy.simplify import rcollect from sympy.utilities import default_sort_key, postfixes


Question: if len(polys) == len(opt.gens) == 2:         f, g = polys         a, b = f.degree_list()        c, d = g.degree_list()        if a <= 2 and b <= 2 and c <= 2 and d <= 2:        if all(i <= 2 for i in f.degree_list() + g.degree_list()):             try:                 return solve_biquadratic(f, g, opt)             except SolveFailed:


Question: if len(G) != 2:         raise SolveFailed     p, q = G     x, y = opt.gens    p, q = G    if not p.gcd(q).is_ground:        # not 0-dimensional        raise SolveFailed      p = Poly(p, x, expand=False)    q = q.ltrim(-1)     p_roots = [ rcollect(expr, y) for expr in roots(p).keys() ]    q = q.ltrim(-1)     q_roots = list(roots(q).keys())      solutions = []


Question: def _is_univariate(f):         """Returns True if 'f' is univariate in its last variable. """         for monom in f.monoms():            if any(m > 0 for m in monom[:-1]):            if any(m for m in monom[:-1]):                 return False          return True


Question: def _eval_subs(self, old, new):         from sympy import exp, log, Symbol         def _check(ct1, ct2, old):            """Return bool, pow where, if bool is True, then the exponent of            Pow `old` will combine with `pow` so the substitution is valid,            otherwise bool will be False,            """Return (bool, pow, remainder_pow) where, if bool is True, then the            exponent of Pow `old` will combine with `pow` so the substitution            is valid, otherwise bool will be False.            For noncommutative objects, `pow` will be an integer, and a factor            `Pow(old.base, remainder_pow)` needs to be included. If there is            no such factor, None is returned. For commutative objects,            remainder_pow is always None.              cti are the coefficient and terms of an exponent of self or old             In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)             will give y**2 since (b**x)**2 == b**(2*x); if that equality does             not hold then the substitution should not occur so `bool` will be             False.             """             coeff1, terms1 = ct1             coeff2, terms2 = ct2             if terms1 == terms2:                pow = coeff1/coeff2                try:                    pow = as_int(pow)                    combines = True                except ValueError:                    combines = Pow._eval_power(                        Pow(*old.as_base_exp(), evaluate=False),                        pow) is not None                return combines, pow            return False, None                if old.is_commutative:                    # Allow fractional powers for commutative objects                    pow = coeff1/coeff2                    try:                        pow = as_int(pow)                        combines = True                    except ValueError:                        combines = Pow._eval_power(                            Pow(*old.as_base_exp(), evaluate=False),                            pow) is not None                    return combines, pow, None                else:                    # With noncommutative symbols, substitute only integer powers                    if not isinstance(terms1, tuple):                        terms1 = (terms1,)                    if not all(term.is_integer for term in terms1):                        return False, None, None                    try:                        # Round pow toward zero                        pow, remainder = divmod(as_int(coeff1), as_int(coeff2))                        if pow < 0 and remainder != 0:                            pow += 1                            remainder -= as_int(coeff2)                        if remainder == 0:                            remainder_pow = None                        else:                            remainder_pow = Mul(remainder, *terms1)                        return True, pow, remainder_pow                    except ValueError:                        # Can't substitute                        pass            return False, None, None          if old == self.base:             return new**self.exp._subs(old, new)

Wrong/surprising result from noncommutative The following behavior in Sympy seems surprising: I would have expected this produces . The issue appears to be that uses fractional powers in the substitution. This then raises questions on what noncommutative symbols in Sympy actually mean mathematically. At least in my use cases for them, certainly does not imply . I would suggest something like the following:


Question: if self.exp.is_Add is False:                 ct1 = self.exp.as_independent(Symbol, as_Add=False)                 ct2 = old.exp.as_independent(Symbol, as_Add=False)                ok, pow = _check(ct1, ct2, old)                ok, pow, remainder_pow = _check(ct1, ct2, old)                 if ok:                     # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2                    return self.func(new, pow)                    result = self.func(new, pow)                    if remainder_pow is not None:                        result = Mul(result, Pow(old.base, remainder_pow))                    return result             else:  # b**(6*x+a).subs(b**(3*x), y) -> y**2 * b**a                 # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))                 oarg = old.exp


Question: for a in self.exp.args:                     newa = a._subs(old, new)                     ct1 = newa.as_coeff_mul()                    ok, pow = _check(ct1, ct2, old)                    ok, pow, remainder_pow = _check(ct1, ct2, old)                     if ok:                         new_l.append(new**pow)                        if remainder_pow is not None:                            o_al.append(remainder_pow)                         continue                    elif not old.is_commutative and not newa.is_integer:                        # If any term in the exponent is non-integer,                        # we do not do any substitutions in the noncommutative case                        return                     o_al.append(newa)                 if new_l:                     new_l.append(Pow(self.base, Add(*o_al), evaluate=False))


Question: ct1 = old.args[0].as_independent(Symbol, as_Add=False)             ct2 = (self.exp*log(self.base)).as_independent(                 Symbol, as_Add=False)            ok, pow = _check(ct1, ct2, old)            ok, pow, remainder_pow = _check(ct1, ct2, old)             if ok:                return self.func(new, pow)  # (2**x).subs(exp(x*log(2)), z) -> z                result = self.func(new, pow)  # (2**x).subs(exp(x*log(2)), z) -> z                if remainder_pow is not None:                    result = Mul(result, Pow(old.base, remainder_pow))                return result      def as_base_exp(self):         """Return base and exp of self.


Question: >>> C == A.row_insert(A.rows, Matrix(B))         True         """        if not self:            return type(self)(other)        # A null matrix can always be stacked (see  #10770)        if self.rows == 0 and self.cols != other.cols:            return self._new(0, other.cols, []).col_join(other)         A, B = self, other         if not A.cols == B.cols:             raise ShapeError()

Behavior of Matrix hstack and vstack changed in sympy 1.1 In sympy 1.0: returns Now, same in sympy 1.1: returns (0, 3) whereas: returns (1, 6)


Question: >>> C == A.col_insert(A.cols, B)         True         """        if not self:            return type(self)(other)        # A null matrix can always be stacked (see  #10770)        if self.cols == 0 and self.rows != other.rows:            return self._new(other.rows, 0, []).row_join(other)         A, B = self, other         if not A.rows == B.rows:             raise ShapeError()


Question: >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5)     {1: x + y, 2: x**2 + x*y, 5: x**3*y**2 + y**5}     >>> decompose(x**2 + x*y + x + y + x**3*y**2 + y**5, True)    [x, y, x**2, y**5, x*y, x**3*y**2]    {x, x**2, y, y**5, x*y, x**3*y**2}     """     expr = S(expr)     poly_dict = {}

decompose() function in intpoly returns a list of arbitrary order The decompose() function, with separate=True, returns , which is ordered arbitrarily. What is this used for? It should be sorted somehow, or returning a set (in which case, why not just use the returned dictionary and have the caller take the values). This is causing test failures for me after some changes to the core. CC


Question: degrees = [(sum(degree_list(monom, *symbols)), monom)                        for monom in expr.args]             if separate:                return [monom[1] for monom in degrees]                return {monom[1] for monom in degrees}             else:                 for monom in degrees:                     degree, term = monom


Question: poly_dict[0] = expr      if separate:        return list(poly_dict.values())        return set(poly_dict.values())     return poly_dict


Question: args.append(a)                     else:                         args.append(newa)                if not _aresame(tuple(args), tail_args):                    tail = self.func(*args)                return self.func(x, tail)                return self.func(x, *args)          # this is the same as above, but there were no pure-number args to         # deal with

Exponent doesn't fully simplify Say I have code like this: The output is How do I simplify it to 0?


Question: args.append(a)             else:                 args.append(newa)        if not _aresame(tuple(args), self.args):            return self.func(*args)        return self        return self.func(*args)      @classmethod     def make_args(cls, expr):


Question: GeneratorsError, ) from sympy.utilities import group, sift, publicfrom sympy.utilities import group, sift, public, filldedent  import sympy.polys import mpmath

degree(multivariate) -degree of first generator When giving the degree function a multivariate expression, the default degree returned is for the first generator which is chosen canonically but arbitrarily. When the degree method of Poly is called, this is not so bad because one would/should know what the generators are. For the case of using the function, however, I believe it allows ambiguity to pass silently by not requiring the generator to be specified. Here, the return value depends on the symbols chosen


Question: from sympy.polys import polyoptions as options from sympy.core.compatibility import iterable, rangefrom sympy.core.compatibility import iterable, range, ordered  @public class Poly(Expr):


Question: p, _ = poly_from_expr(f.as_expr())         if gen not in p.gens:             return S.Zero<ins>    elif not f.is_Poly and len(f.free_symbols) > 1:        raise TypeError(filldedent('''         A symbolic generator of interest is required for a multivariate         expression like func = %s, e.g. degree(func, gen = %s) instead of         degree(func, gen = %s).        ''' % (f, next(ordered(f.free_symbols)), gen)))</ins>      return Integer(p.degree(gen))


Question: if p.is_infinite or q.is_infinite or p is nan or q is nan:                 return nan             if (p == q or p == -q or                    p.is_Pow and p.exp.is_Integer and p.base == q or                    p.is_Pow and p.exp.is_integer and p.base == q and q.is_integer                    and p.exp.is_positive or                     p.is_integer and q == 1):                 return S.Zero

Mod(x2, x) is not (always) 0 When the base is not an integer, is not 0. The base is not tested to be an integer in Mod's eval logic: so but


Question: Substitutions containing any Symbol from ``ignore`` will be ignored.     """     from sympy.matrices.expressions import MatrixExpr, MatrixSymbol, MatMul, MatAdd<ins>    from sympy.matrices.expressions.matexpr import MatrixElement</ins>      if opt_subs is None:         opt_subs = dict()

cse() has strange behaviour for MatrixSymbol indexing Example: This gives the following output: and are just copies of the matrices and , respectively.


Question: if not isinstance(expr, (Basic, Unevaluated)):             return         if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order):        if isinstance(expr, Basic) and (expr.is_Atom or expr.is_Order or isinstance(expr, MatrixSymbol) or isinstance(expr, MatrixElement)):             if expr.is_Symbol:                 excluded_symbols.add(expr)             return