Debian Codegraph @

wxgeometrie/mathlib/printers.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------#######
4 # Mathlib 2 (sympy powered) #
5 ##--------------------------------------#######
6 #WxGeometrie
7 #Dynamic geometry, graph plotter, and more for french mathematic teachers.
8 #Copyright (C) 2005-2013 Nicolas Pourcelot
9 #
10 #This program is free software; you can redistribute it and/or modify
11 #it under the terms of the GNU General Public License as published by
12 #the Free Software Foundation; either version 2 of the License, or
13 #(at your option) any later version.
14 #
15 #This program is distributed in the hope that it will be useful,
16 #but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 #GNU General Public License for more details.
19 #
20 #You should have received a copy of the GNU General Public License
21 #along with this program; if not, write to the Free Software
22 #Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23
24 ## Surclasse les printers de sympy
25
26 from math import floor, log
27
28 from sympy import Symbol, Integer, Float, Basic, FunctionClass, I, Mul
29 # from sympy.core.core import BasicMeta
30 from sympy.printing.latex import LatexPrinter
31 from sympy.printing.str import StrPrinter
32 from sympy.core import S
33
34 from .custom_objects import Decim
35
36
37 class MyCustomPrinter(object):
38 """Personnalisation du printer de sympy.
39
40 * implémentation de méthodes génériques pour gérer les objets Decim.
41 * changement de l'ordre de recherche des méthodes d'impression :
42 on cherche d'abord l'existence d'une méthode _print_ClasseObjet,
43 avant de regarder si l'objet a une méthode ._latex() ou ._str().
44
45 Ceci facilite la personnalisation de l'impression : il est plus
46 propre de rajouter une méthode au printer que de modifier les
47 méthodes d'impressions de nombreux objets par surclassage ou
48 par "Monkey Patching" !
49 """
50
51 def _print(self, expr, *args, **kwargs):
52 """Internal dispatcher
53
54 Tries the following concepts to print an expression:
55 1. Take the best fitting method defined in the printer.
56 2. Let the object print itself if it knows how.
57 3. As fall-back use the emptyPrinter method for the printer.
58 """
59 self._print_level += 1
60 try:
61 # See if the class of expr is known, or if one of its super
62 # classes is known, and use that print function
63 for cls in type(expr).__mro__:
64 printmethod = '_print_' + cls.__name__
65 if hasattr(self, printmethod):
66 return getattr(self, printmethod)(expr, *args, **kwargs)
67
68 # If the printer defines a name for a printing method
69 # (Printer.printmethod) and the object knows for itself how it
70 # should be printed, use that method.
71 if (self.printmethod and hasattr(expr, self.printmethod)) :
72 # and not isinstance(expr, BasicMeta)):
73 return getattr(expr, self.printmethod)(self, *args, **kwargs)
74
75 # Unknown object, fall back to the emptyPrinter.
76 return self.emptyPrinter(expr)
77 finally:
78 self._print_level -= 1
79
80 def _convert_Decim(self, expr):
81 conv = self._convert_Decim
82 if isinstance(expr, FunctionClass):
83 return expr
84 elif hasattr(expr, 'atoms') and hasattr(expr, 'subs'):
85 dico = {}
86 for a in expr.atoms():
87 if a.is_Rational and isinstance(a, Decim):
88 dico[a] = Float(a, dps=60)
89 expr = expr.subs(dico).subs(Float(1), S.One)
90 elif isinstance(expr, (list, tuple)):
91 return expr.__class__(conv(item) for item in expr)
92 elif isinstance(expr, dict):
93 return dict((conv(key), conv(val)) for key, val in expr.items())
94 return expr
95
96 def _float_evalf(self, expr):
97 "Évalue le flottant en respectant le réglage du printer (nombre de décimales)."
98 if self._settings['mode_scientifique']:
99 decimales = self._settings['decimales_sci'] + 1
100 else:
101 decimales = self._settings['decimales']
102 # Le nombre de décimales ne doit pas dépasser la précision interne
103 # du flottant, au risque d'ajouter des décimales fausses.
104 # Cette précision interne est notée en bits, qu'il faut convertir en
105 # nombre de décimales.
106 # Nota: log(2)/log(10) = 0.3010299956639812
107 precision_interne = round(expr._prec*0.3010299956639812) - 1
108 decimales = max(min(decimales, precision_interne), 1)
109 return expr.evalf(decimales)
110
111
112 class CustomStrPrinter(MyCustomPrinter, StrPrinter):
113 def __init__(self, settings):
114 defaults = {'decimales': 18,
115 'mode_scientifique': False,
116 'decimales_sci': 2
117 }
118 self._default_settings.update(defaults)
119 StrPrinter.__init__(self, settings)
120
121 def _print_str(self, expr):
122 # Ne pas utiliser repr(), car on veut tjs avoir des guillemets doubles
123 # à l'extérieur de la chaîne (pour éviter les confusions avec le ' de
124 # la dérivée).
125 return '"%s"' % expr.replace('"', r'\"')
126
127 def _print_Exp1(self, expr):
128 return 'e'
129
130 def _print_Abs(self, expr):
131 return 'abs(%s)' % self._print(expr.args[0])
132
133 def _print_ImaginaryUnit(self, expr):
134 return 'i'
135
136 def _print_Infinity(self, expr):
137 return '+oo'
138
139 def _print_log(self, expr):
140 return "ln(%s)" % self.stringify(expr.args, ", ")
141
142 def _print_Pow(self, *args, **kw):
143 return StrPrinter._print_Pow(self, *args, **kw).replace('**', '^')
144
145 def _print_Float(self, expr):
146 exposant = None
147 if self._settings['mode_scientifique']:
148 # Conversion en écriture scientifique.
149 puissance = int(floor(log(expr, 10)))
150 flottant = self._float_evalf(expr*10**-puissance)
151 mantisse = StrPrinter._print_Float(self, flottant)
152 exposant = str(puissance)
153 else:
154 chaine = StrPrinter._print_Float(self, self._float_evalf(expr))
155 if 'e' in chaine:
156 # Déjà en mode scientifique (ex: 1.3e-15)
157 mantisse, exposant = chaine.split('e')
158
159 if exposant is not None:
160 # Affichage en mode scientifique
161 mantisse = mantisse.rstrip('0')
162 # On laisse la mantisse sous forme de flottant.
163 # Ainsi, '2,00000*10^-8' devient '2,0*10^-8', et non '2*10^-8'.
164 # Lorsqu'on sauvegarde l'état de l'interprète de la calculatrice,
165 # les décimaux du type 0,00000002 sont ainsi sauvegardés sous
166 # forme décimale, et non sous forme fractionnaire.
167 if mantisse.endswith('.'):
168 mantisse += '0'
169 exposant = exposant.lstrip('+')
170 return '%s*10^%s' % (mantisse, exposant)
171 else:
172 # Par contre, lorsque les décimaux sont des entiers, inutile de les
173 # sauvegarder sous forme décimale.
174 return chaine.rstrip('0').rstrip('.')
175
176 def _print_Union(self, expr):
177 return expr.__str__()
178
179 def _print_set(self, expr):
180 return '{%s}' % ' ; '.join(self._print(val) for val in expr)
181
182 def _print_Fonction(self, expr):
183 return "%s -> %s" % (", ".join(expr._variables()),
184 self._print(self._convert_Decim(expr.expression)))
185
186 def doprint(self, expr):
187 # Mieux vaut faire la substitution une seule fois dès le départ.
188 expr = self._convert_Decim(expr)
189 return StrPrinter.doprint(self, expr)
190
191 def custom_str(expr, **settings):
192 return CustomStrPrinter(settings).doprint(expr)
193
194 # Modifie Basic.__repr__ pour utiliser `custom_str` au lieu de `sstr` (printer de sympy)
195 # Can't use partial() for this (cf. http://bugs.python.org/issue4331)
196
197 Basic.__repr__ = (lambda self: custom_str(self, order=None))
198
199
200 class CustomLatexPrinter(MyCustomPrinter, LatexPrinter):
201
202 def __init__(self, settings):
203 defaults = {'decimales': 18,
204 'mode_scientifique': False,
205 'decimales_sci': 2,
206 "mat_str" : "pmatrix",
207 "mat_delim" : "",
208 "mode": "inline",
209 "fold_frac_powers": False,
210 "fold_short_frac": False,
211 }
212 self._default_settings.update(defaults)
213 LatexPrinter.__init__(self, settings)
214
215 def _print_Temps(self, expr):
216 return r"%s \mathrm{j}\, %s \mathrm{h}\, %s \mathrm{min}\, %s \mathrm{s}" % expr.jhms()
217
218 def _print_exp(self, expr, exp=None):
219 tex = r"\mathrm{e}^{%s}" % self._print(expr.args[0])
220 return self._do_exponent(tex, exp)
221
222 def _print_Exp1(self, expr):
223 return r"\mathrm{e}"
224
225 def _print_Abs(self, *args, **kw):
226 res = LatexPrinter._print_Abs(self, *args, **kw)
227 return res.replace(r'\lvert', r'|').replace(r'\rvert', r'|')
228
229 def _print_Pi(self, *args, **kw):
230 return r"\pi"
231
232 def _print_ImaginaryUnit(self, expr):
233 return r"\mathrm{i}"
234
235 def _print_Fonction(self, expr):
236 return ", ".join(expr._variables()) + "\\mapsto " + self._print(expr.expression)
237
238 def _print_Function(self, expr, exp=None):
239 func = expr.func.__name__
240
241 if hasattr(self, '_print_' + func):
242 return getattr(self, '_print_' + func)(expr, exp)
243
244 else:
245 if exp is not None:
246 name = r"\mathrm{%s}^{%s}" % (func, exp)
247 else:
248 name = r"\mathrm{%s}" % func
249 if len(expr.args) == 1 and isinstance(expr.args[0], (Symbol, Integer)):
250 return name + "(" + str(self._print(expr.args[0])) +")"
251 else:
252 args = [ str(self._print(arg)) for arg in expr.args ]
253 return name + r"\left(%s\right)" % ",".join(args)
254
255 def _print_ProduitEntiers(self, expr):
256 def formater(exposant):
257 if exposant == 1:
258 return ""
259 return "^" + str(exposant)
260 return "\\times ".join((str(entier) + formater(exposant)) for entier, exposant in expr.couples)
261
262 def _print_Float(self, expr):
263 if self._settings['mode_scientifique']:
264 # Gestion de l'écriture scientifique.
265 n = int(floor(log(expr, 10)))
266 s = LatexPrinter._print_Float(self, self._float_evalf(expr*10**-n))
267 return r"%s \times 10^{%s}" % (s, n)
268 s = LatexPrinter._print_Float(self, self._float_evalf(expr))
269 if s.startswith(r'1.0 \times '): # sympy 0.7.3
270 return s[11:]
271 elif s.startswith(r'1.0 \cdot '): # sympy 0.7.5
272 return s[10:]
273 elif r'\times' not in s:
274 # Ne pas supprimer un zéro de la puissance !
275 s = s.rstrip('0').rstrip('.')
276 return s
277
278 def _print_Infinity(self, expr):
279 return r"+\infty"
280
281 def _print_Order(self, expr):
282 return r"\mathcal{O}\left(%s\right)" % \
283 self._print(expr.args[0])
284
285 def _print_Union(self, expr):
286 if expr.vide:
287 return r"\varnothing"
288 tex = r"\cup".join(self._print(intervalle) for intervalle in expr.intervalles)
289 tex = tex.replace(r"\right\}\cup\left\{", "\,;\, ")
290 return tex
291
292 def _print_Mul(self, expr):
293 args = expr.args
294 if args[-1] is I:
295 if len(args) == 2 and args[0] == -1:
296 return LatexPrinter._print_Mul(self, expr)
297 return '%s %s' % (self._print(Mul(*args[:-1])), self._print(I))
298 return LatexPrinter._print_Mul(self, expr)
299 #return ' '.join(self._print(arg) for arg in expr.args)
300
301 def _print_set(self, expr):
302 if expr:
303 return r'\left\{%s\right\}' % '\,;\,'.join(self._print(val) for val in expr)
304 return r"\emptyset"
305
306 def _print_Intervalle(self, expr):
307 if expr.vide:
308 return r"\varnothing"
309 elif expr.inf_inclus and expr.sup_inclus and expr.inf == expr.sup:
310 return r"\left\{%s\right\}" % self._print(expr.inf)
311 if expr.inf_inclus:
312 left = r"\left["
313 else:
314 left = r"\left]"
315 if expr.sup_inclus:
316 right = r"\right]"
317 else:
318 right = r"\right["
319 return r"%s%s;%s%s" % (left, self._print(expr.inf), self._print(expr.sup), right)
320
321 def _print_tuple(self, expr):
322 return r"\left(" + ",\,".join(self._print(item) for item in expr) + r"\right)"
323
324 def _print_log(self, expr, exp=None):
325 if len(expr.args) == 1 and isinstance(expr.args[0], (Symbol, Integer)):
326 tex = r"\ln(%s)" % self._print(expr.args[0])
327 else:
328 tex = r"\ln\left(%s\right)" % self._print(expr.args[0])
329 return self._do_exponent(tex, exp)
330
331 def _print_function(self, expr):
332 return r"\mathrm{Fonction}\, " + expr.__name__
333
334 def _print_Decim(self, expr):
335 return self._print_Float(Float(expr, dps=expr.prec))
336
337 def doprint(self, expr):
338 expr = self._convert_Decim(expr)
339 tex = LatexPrinter.doprint(self, expr)
340 return tex.replace(r'\operatorname{', r'\mathrm{')
341
342
343 def custom_latex(expr, **settings):
344 return CustomLatexPrinter(settings).doprint(expr)