K i=dZddlmZddlZddlmZmZddlZddlm Z ddl m Z m Z ddl mZddlmZdd lmZmZmZe d ZGd d ZGd dZdZy)a&Printing subsystem driver SymPy's printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression. **The basic concept is the following:** 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Which Method is Responsible for Printing? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The whole printing process is started by calling ``.doprint(expr)`` on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps: 1. **Let the object print itself if it knows how.** The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under ``Printer.printmethod``. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. Look at the documentation of the printer that you want to use. The name of the method is specified there. This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in SymPy objects, but not that good for user defined classes where it is inconvenient to patch the printers. 2. **Take the best fitting method defined in the printer.** The printer loops through expr classes (class + its bases), and tries to dispatch the work to ``_print_`` e.g., suppose we have the following class hierarchy:: Basic | Atom | Number | Rational then, for ``expr=Rational(...)``, the Printer will try to call printer methods in the order as shown in the figure below:: p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr) if ``._print_Rational`` method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ``._print_Number`` and so on. 3. **As a fall-back use the emptyPrinter method for the printer.** As fall-back ``self.emptyPrinter`` will be called with the expression. If not defined in the Printer subclass this will be the same as ``str(expr)``. .. _printer_example: Example of Custom Printer ^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, we have a printer which prints the derivative of a function in a shorter form. .. code-block:: python from sympy.core.symbol import Symbol from sympy.printing.latex import LatexPrinter, print_latex from sympy.core.function import UndefinedFunction, Function class MyLatexPrinter(LatexPrinter): """Print derivative of a function of symbols in a shorter form. """ def _print_Derivative(self, expr): function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or \ not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) # If you want the printer to work correctly for nested # expressions then use self._print() instead of str() or latex(). # See the example of nested modulo below in the custom printing # method section. return "{}_{{{}}}".format( self._print(Symbol(function.func.__name__)), ''.join(self._print(i) for i in vars)) def print_my_latex(expr): """ Most of the printers define their own wrappers for print(). These wrappers usually take printer settings. Our printer does not have any settings. """ print(MyLatexPrinter().doprint(expr)) y = Symbol("y") x = Symbol("x") f = Function("f") expr = f(x, y).diff(x, y) # Print the expression using the normal latex printer and our custom # printer. print_latex(expr) print_my_latex(expr) The output of the code above is:: \frac{\partial^{2}}{\partial x\partial y} f{\left(x,y \right)} f_{xy} .. _printer_method_example: Example of Custom Printing Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method ``_latex`` of ``Mod``. >>> from sympy import Symbol, Mod, Integer, print_latex >>> # Always use printer._print() >>> class ModOp(Mod): ... def _latex(self, printer): ... a, b = [printer._print(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b) Comparing the output of our custom operator to the builtin one: >>> x = Symbol('x') >>> m = Symbol('m') >>> print_latex(Mod(x, m)) x \bmod m >>> print_latex(ModOp(x, m)) \operatorname{Mod}{\left(x, m\right)} Common mistakes ~~~~~~~~~~~~~~~ It's important to always use ``self._print(obj)`` to print subcomponents of an expression when customizing a printer. Mistakes include: 1. Using ``self.doprint(obj)`` instead: >>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b) This fails when the ``mode`` argument is passed to the printer: >>> print_latex(ModOp(x, m), mode='inline') # ok $\operatorname{Mod}{\left(x, m\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\operatorname{Mod}{\left($x$, $m$\right)}$ 2. Using ``str(obj)`` instead: >>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b) This fails on nested objects: >>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \operatorname{Mod}{\left(\operatorname{Mod}{\left(x, m\right)}, 7\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \operatorname{Mod}{\left(ModOpNestedWrong(x, m), 7\right)} 3. Using ``LatexPrinter()._print(obj)`` instead. >>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b) This causes all the settings to be discarded in the subobjects. As an example, the ``full_prec`` setting which shows floats to full precision is ignored: >>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \operatorname{Mod}{\left(1.00000000000000 x, m\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \operatorname{Mod}{\left(1.0 x, m\right)} ) annotationsN)AnyType)contextmanager) cmp_to_keyupdate_wrapper)Add)Basic) AppliedUndefUndefinedFunctionFunctionc+K|jj} |jj|d||_y#||_wxYwwN)_contextcopyupdate)printerkwargsoriginals \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/printing/printer.pyprinter_contextrsF$$&H$' #8sAAA AAceZdZUdZiZded<iZded<dZedZ ddZ edZ e d Z d Zdd Zd Zdd ZdZy)Printerz Generic printer Its job is to provide infrastructure for implementing new printers easily. If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example_ . zdict[str, Any]_global_settings_default_settingsNc|jj}|jjD]\}}||jvs|||<|Sr)rrritemsclssettingskeyvals r_get_initial_settingszPrinter._get_initial_settingssV((--/,,224 $HCc+++ #  $cJt|_|j|_i|_|s|jj |t |jt |jkDr-|jD]}||jvstd|zd|_ y)NzUnknown setting '%s'.r) str_strr# _settingsrrlenr TypeError _print_level)selfr r!s r__init__zPrinter.__init__s 335   NN ! !( +4>>"S)?)?%@@>>GC$"8"88'(?#(EFFG r$c X|jD]\}}| ||j|<y)z#Set system-wide printing settings. N)rrrs rset_global_settingszPrinter.set_global_settingss3!( 0HC,/$$S) 0r$cRd|jvr|jdStd)NorderzNo order defined.)r(AttributeErrorr,s rr1z Printer.orders) dnn $>>'* * !45 5r$cB|j|j|S)z7Returns printer's representation for expr (as a string))r'_printr,exprs rdoprintzPrinter.doprint#syyT*++r$c @|xjdz c_ |jrht||jrRt|trt |t s2t||j|fi||xjdzc_St |jtvrjtdtvrjtdtvr2jt}tfdd|D|dzD]@}d|jz}t||d}|"||fi|c|xjdzc_S|j||xjdzc_S#|xjdzc_wxYw)a#Internal dispatcher Tries the following concepts to print an expression: 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Nc3K|]=}|jdjk(s|jjdr|?yw)rBaseN)__name__endswith).0cclassess r z!Printer._print..Es@ 1aJJ'!*"5"55JJ''/!" 1sAA_print_)r+ printmethodhasattr isinstancetype issubclassr getattr__mro__r indexr r tupler= emptyPrinter)r,r7rirprintmethodnamerDrAs @rr5zPrinter._print's Q #GD$2B2B$C"4.:dE3J:74)9)9:4J6J4    " )4j((Gw&!'-- "=">? G+!'--0A"B"CD7"MM(+ 172A; 113:12;? 7"+cll":%dOTB *&t6v66    "  7 $$T*    " D   " sAF B2F? FFFct|Sr)r&r6s rrMzPrinter.emptyPrinterRs 4yr$c|xs |j}|dk(r3ttj|t |j S|dk(rt |jS|j|S)z4A compatibility function for ordering terms in Add. old)r!none)r1) r1sortedr make_argsr_compare_prettylistargsas_ordered_terms)r,r7r1s r_as_ordered_termszPrinter._as_ordered_termsUsa# E>#---:d>R>R3ST T f_ ? "((u(5 5r$cRddlm}ddlm}ddlm}t ||r t ||syt ||s t ||ryt ||rIt ||r=|j|jz}|j|jz}||kD||kz S|d|d|d } } }|j|| | zz} | rH| | vrD| | } |j|| | zz} | r&| | vr"| | }tj| |}|dk7r|Stj||S) aTreturn -1, 0, 1 if a is canonically less, equal or greater than b. This is used when 'order=old' is selected for printing. This puts Order last, orders Rationals according to value, puts terms in order wrt the power of the last power appearing in a term. Ties are broken using Basic.compare. r)Rational)Wild)Orderr:p1p2p3) sympy.core.numbersr\sympy.core.symbolr]sympy.series.orderr^rFpqmatchr compare)r,abr\r]r^lrr`rarbr_aa3r_bb3r@s rrVzPrinter._compare_pretty`s 0*, a  1e(<!U# 1e(< a "z!X'>acc Aacc AEa!e$ $dT$ZdBB''"r2v+&CrSyWggb2r6k*29RB b"-AAv }}Q""r$r)returnr&)r= __module__ __qualname____doc__r__annotations__rrD classmethodr#r-r/propertyr1r8r5rMrZrVr$rrrs(*n)(*~*K$00 66 ,)#V 6!#r$rc6eZdZdZddZdZdZeddZy) _PrintFunctionz[ Function wrapper to replace ``**settings`` in the signature with printer defaults cttj|jj }|j dj tjjk(sJ||_ ||_ t||y)Nr_) rWinspect signature parametersvaluespopkind Parameter VAR_KEYWORD_PrintFunction__other_params_PrintFunction__print_clsr)r,f print_clsparamss rr-z_PrintFunction.__init__shg''*55<<>?zz"~""g&7&7&C&CCCC$$tQr$c.|jjSr) __wrapped__rtr3s r __reduce__z_PrintFunction.__reduce__s,,,r$c&|j|i|Sr)r)r,rXrs r__call__z_PrintFunction.__call__st000r$c |jj}tj|j|j Dcgc]5\}}tj |tj j|7c}}z|jjjdtjjScc}}w)N)defaultrr)rreturn_annotation) rr#r} Signaturerrr KEYWORD_ONLYrrvgetempty)r,r kvs r __signature__z_PrintFunction.__signature__s##99;  **$NN,.Aq!!!W%6%6%C%CQO.#..>>BB8WM^M^MdMde   .s:C N)rz Type[Printer])rrzinspect.Signature) r=rsrtrur-rrrxrryr$rr{r{s* - 1  r$r{cfd}|S)zJ A decorator to replace kwargs with the printer settings in __signature__ ctjdkr,t|jdtfd|j i}nt}||S)N) r{ru)sys version_inforGrtr{ru)rrrs r decoratorz!print_function..decoratorsN   f $!..)8>:KiYZYbYbMcdC C1i  r$ry)rrs` rprint_functionrs! r$)ru __future__rrtypingrrr} contextlibr functoolsrrsympy.core.addr sympy.core.basicr sympy.core.functionr r r rrr{rryr$rrs]Pd# %0"II$$V#V#r  D r$