| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
from math import floor, log |
| 27 |
|
| 28 |
from sympy import Symbol, Integer, Float, Basic, FunctionClass, I, Mul |
| 29 |
|
| 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 |
|
| 62 |
|
| 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 |
|
| 69 |
|
| 70 |
|
| 71 |
if (self.printmethod and hasattr(expr, self.printmethod)) : |
| 72 |
|
| 73 |
return getattr(expr, self.printmethod)(self, *args, **kwargs) |
| 74 |
|
| 75 |
|
| 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 |
rne |
| 103 |
. |
| 104 |
en |
| 105 |
. |
| 106 |
|
| 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 |
|
| 123 |
' de |
| 124 |
). |
| 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 |
. |
| 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 |
5) |
| 157 |
mantisse, exposant = chaine.split('e') |
| 158 |
|
| 159 |
if exposant is not None: |
| 160 |
|
| 161 |
mantisse = mantisse.rstrip('0') |
| 162 |
|
| 163 |
|
| 164 |
e, |
| 165 |
us |
| 166 |
. |
| 167 |
if mantisse.endswith('.'): |
| 168 |
mantisse += '0' |
| 169 |
exposant = exposant.lstrip('+') |
| 170 |
return '%s*10^%s' % (mantisse, exposant) |
| 171 |
else: |
| 172 |
s |
| 173 |
. |
| 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 |
t. |
| 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 |
|
| 195 |
|
| 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 |
. |
| 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 '): |
| 270 |
return s[11:] |
| 271 |
elif s.startswith(r'1.0 \cdot '): |
| 272 |
return s[10:] |
| 273 |
elif r'\times' not in s: |
| 274 |
! |
| 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\{", r"\,;\, ") |
| 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 |
|
| 300 |
|
| 301 |
def _print_set(self, expr): |
| 302 |
if expr: |
| •303 |
return r'\left\{%s\right\}' % r'\,;\,'.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(" + r",\,".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) |