| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
import keyword, re |
| 25 |
|
| 26 |
import matplotlib |
| 27 |
from matplotlib.mathtext import MathTextParser |
| 28 |
_mathtext_raw_parser = MathTextParser("path").parse |
| 29 |
xt |
| 30 |
: |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
from sympy import Expr |
| 35 |
|
| 36 |
from ..pylib.fonctions import regsub, split_around_parenthesis, debug, \ |
| 37 |
warning, rreplace |
| 38 |
from .. import param |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
ire) |
| 43 |
dictionnaire_latex_commandes = { |
| 44 |
"nombre" : "", |
| 45 |
"nb": "", |
| 46 |
"left": "", |
| 47 |
"right": "", |
| 48 |
"sqrt": " sqrt", |
| 49 |
"sin": " sin", |
| 50 |
"cos": " cos", |
| 51 |
"tan": " tan", |
| 52 |
"ln":" ln", |
| 53 |
"log": " log", |
| 54 |
"exp": " exp", |
| 55 |
"times": "*", |
| 56 |
"infty": "oo", |
| 57 |
"oo": "oo", |
| 58 |
"i": " i", |
| 59 |
"e": " e", |
| 60 |
"pi": " pi", |
| 61 |
"quad": " ", |
| 62 |
"qquad": " ", |
| 63 |
"text": "", |
| 64 |
"mathrm": "", |
| 65 |
"bar": "conjug", |
| 66 |
"le": "<=", |
| 67 |
"leqslant": "<=", |
| 68 |
"ge": ">=", |
| 69 |
"geqslant": ">=", |
| 70 |
"displaystyle": "", |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
ues |
| 75 |
dictionnaire_latex_special = { |
| 76 |
"~": " ", |
| 77 |
"\\,": " ", |
| 78 |
"\\!": " ", |
| 79 |
"\\;": " ", |
| 80 |
"\\:": " ", |
| 81 |
"\\\\": " ", |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
VAR = "(?:[_A-Za-z][_A-Za-z0-9]*)" |
| 86 |
|
| 87 |
VAR_NOT_ATTR = "(?:(?<![.A-Za-z0-9_])[A-Za-z_][A-Za-z0-9_]*)" |
| 88 |
|
| 89 |
|
| 90 |
t |
| 91 |
NBR_SIGNE = "(?:(?<![.A-Za-z0-9_])(?:(((?<=[*/^()])|^)[+-])?[ ]?(?:[0-9]*[.][0-9]+|[0-9]+[.]?)))" |
| 92 |
|
| 93 |
NBR = "(?:(?<![.A-Za-z0-9_])(?:[0-9]*[.][0-9]+|[0-9]+[.]?))" |
| 94 |
int) |
| 95 |
NBR_FLOTTANT = "(?:(?<![.A-Za-z0-9_])(?:[0-9]+[.][0-9]+))" |
| 96 |
oint) |
| 97 |
NBR_VIRGULE = "(?:(?<![.A-Za-z0-9_])(?:[0-9]+[,][0-9]+))" |
| 98 |
|
| 99 |
NBR_OR_VAR = "(?:" + NBR + "|" + VAR + ")" |
| 100 |
NBR_SIGNE_OR_VAR = "(?:" + NBR_SIGNE + "|" + VAR + ")" |
| 101 |
) |
| •102 |
LISTE_SIMPLE = r"\[[^][]+\]" |
| 103 |
|
| 104 |
MATRICE = r"\[ ?(%s ?, ?)*(%s) ?\]" % (LISTE_SIMPLE, LISTE_SIMPLE) |
| 105 |
|
| 106 |
|
| 107 |
def _simplifier(formule): |
| 108 |
"""Suppressions d'espaces inutiles.""" |
| 109 |
|
| 110 |
t |
| 111 |
|
| 112 |
s. |
| 113 |
formule = regsub("(?<![A-Za-z0-9_.])[ ]", formule, "") |
| 114 |
formule = regsub("[ ](?![A-Za-z0-9_.])", formule, "") |
| 115 |
return formule |
| 116 |
|
| 117 |
def _arguments_latex(chaine, nbr_arguments = 2): |
| 118 |
"""Renvoie les arguments d'une commande LaTeX (ainsi que le reste de la chaîne). |
| 119 |
|
| 120 |
>>> from wxgeometrie.mathlib.parsers import _arguments_latex |
| 121 |
>>> _arguments_latex('2{x+1}+4', 2) |
| 122 |
['2', '{x+1}', '+4'] |
| 123 |
>>> _arguments_latex('{x+2}5+4x-17^{2+x}', 2) |
| 124 |
['{x+2}', '5', '+4x-17^{2+x}'] |
| 125 |
""" |
| 126 |
liste = [] |
| 127 |
while len(liste) < nbr_arguments: |
| 128 |
if not chaine: |
| 129 |
raise TypeError("Il manque des arguments.") |
| 130 |
if chaine[0] != "{": |
| 131 |
liste.append(chaine[0]) |
| 132 |
chaine = chaine[1:] |
| 133 |
else: |
| 134 |
l = split_around_parenthesis(chaine, 0, "{") |
| 135 |
if len(l) != 3: |
| 136 |
raise TypeError("Arguments mal formes: il manque des '}'.") |
| 137 |
liste.append(l[1]) |
| 138 |
chaine = l[2] |
| 139 |
liste.append(chaine) |
| 140 |
return liste |
| 141 |
|
| 142 |
|
| 143 |
def _convertir_latex_frac(chaine): |
| •144 |
r"""Convertit \frac{a}{b}, \dfrac{a}{b} et \tfrac{a}{b} en ((a)/(b)). |
| 145 |
|
| 146 |
>>> from wxgeometrie.mathlib.parsers import _convertir_latex_frac |
| 147 |
>>> _convertir_latex_frac('3+\dfrac{1}{2x+1}+5x+1') |
| 148 |
'3+((1)/(2x+1))+5x+1' |
| 149 |
""" |
| 150 |
for substr in (r"\frac", r"\dfrac", r"\tfrac"): |
| 151 |
i = chaine.find(substr) |
| 152 |
while i != -1: |
| 153 |
arg1, arg2, reste = _arguments_latex(chaine[i + len(substr):], 2) |
| 154 |
if arg1[0] == '{' and arg1[-1] == '}': |
| 155 |
arg1 = '(' + arg1[1:-1] + ')' |
| 156 |
if arg2[0] == '{' and arg2[-1] == '}': |
| 157 |
arg2 = '(' + arg2[1:-1] + ')' |
| 158 |
chaine = chaine[:i] + "(" + arg1 + "/" + arg2 + ")" + reste |
| 159 |
i = chaine.find(substr, i) |
| 160 |
return chaine |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
def _ajouter_mult_manquants(formule, fonctions = (), verbose = None, mots_cles = ()): |
| 165 |
if isinstance(fonctions, dict): |
| 166 |
ms |
| 167 |
|
| 168 |
fonctions = [key for key, val in fonctions.items() if hasattr(val, "__call__") and not isinstance(val, Expr)] |
| 169 |
|
| 170 |
if verbose: |
| 171 |
print('1', formule) |
| 172 |
|
| 173 |
|
| 174 |
formule = regsub(NBR + "[ ]?(?=[a-zA-Z_])", formule, lambda s: s.rstrip() + '*') |
| 175 |
s |
| 176 |
|
| 177 |
|
| 178 |
formule = formule.replace(")(",")*(") |
| 179 |
|
| 180 |
if verbose: |
| 181 |
print('2', formule) |
| 182 |
|
| 183 |
|
| 184 |
def f1(s): |
| 185 |
s = s.strip() |
| 186 |
if s in fonctions: |
| 187 |
return s |
| 188 |
elif s[0] == '.' and not s[1:].isdigit(): |
| 189 |
e |
| 190 |
nt |
| 191 |
|
| 192 |
return s |
| 193 |
else: |
| 194 |
return s + "*" |
| 195 |
formule = regsub("[.]?" + NBR_OR_VAR + "[ ]?(?=[(])", formule, f1) |
| 196 |
|
| 197 |
if verbose: |
| 198 |
print('3', formule) |
| 199 |
|
| 200 |
|
| 201 |
. |
| 202 |
) |
| 203 |
def f2(s): |
| 204 |
l = s.split() |
| 205 |
if any((elt in mots_cles) for elt in l): |
| 206 |
return s |
| 207 |
elif l[0] in fonctions: |
| 208 |
return l[0] + "(" + l[1] + ")" |
| 209 |
else: |
| 210 |
return l[0] + "*" + l[1] |
| 211 |
formule_initiale = "" |
| 212 |
i = 0 .. |
| 213 |
while formule != formule_initiale and i < 1000: |
| 214 |
formule_initiale = formule |
| 215 |
formule = regsub(VAR + "[ ]" + NBR + "?[*/]?" + NBR_OR_VAR , formule, f2) |
| 216 |
i += 1 |
| 217 |
|
| 218 |
if verbose: |
| 219 |
print('4', formule) |
| 220 |
|
| 221 |
|
| •222 |
formule = regsub(r"[)][ ]?\w", formule, lambda s: s[0] + '*' + s[-1]) |
| 223 |
s |
| 224 |
|
| 225 |
t. |
| 226 |
mc = '|'.join(mots_cles) |
| 227 |
formule = regsub("(?<![A-Za-z0-9_])(%s)[*]" %mc, formule, lambda s:s[:-1] + ' ') |
| 228 |
formule = regsub("[*](%s)(?![A-Za-z0-9_])" %mc, formule, lambda s:' ' + s[1:]) |
| 229 |
|
| 230 |
return formule |
| 231 |
|
| 232 |
|
| 233 |
def _convertir_separateur_decimal(s): |
| 234 |
s = regsub(NBR_VIRGULE, s, (lambda s: s.replace(',', '.'))) |
| 235 |
return s.replace(';', ',') |
| 236 |
|
| 237 |
|
| 238 |
def extraire_chaines(chaine): |
| 239 |
"""Extrait les chaînes de caractères trouvées dans `chaine`. |
| 240 |
|
| 241 |
Chaque chaîne interne est remplacée par <@> (et le symbole @ lui-même |
| 242 |
est remplacé par @@). |
| 243 |
La fonction renvoie la chaîne ainsi modifiée, et une liste des chaînes |
| 244 |
internes extraites. |
| 245 |
|
| 246 |
Exemple:: |
| 247 |
|
| 248 |
>>> from wxgeometrie.mathlib.parsers import extraire_chaines as extraire |
| 249 |
>>> chaine = '''Voici une chaine: 'Bonjour ' et une autre: "l'ami !"''' |
| 250 |
>>> chaine, sous_chaines = extraire(chaine) |
| 251 |
>>> chaine |
| 252 |
'Voici une chaine: <@> et une autre: <@>' |
| 253 |
>>> sous_chaines |
| 254 |
["'Bonjour '", '"l\\'ami !"'] |
| 255 |
""" |
| 256 |
. |
| 257 |
fin = 0 |
| 258 |
|
| 259 |
position = 0 |
| 260 |
lu. |
| 261 |
mode = None |
| 262 |
reste = [] |
| 263 |
chaines = [] |
| 264 |
|
| 265 |
chaine = chaine.replace('@', '@@') |
| 266 |
|
| 267 |
for i in range(10000): |
| 268 |
if mode is None: |
| 269 |
e. |
| 270 |
debut1 = chaine.find("'", position) |
| 271 |
debut2 = chaine.find('"', position) |
| 272 |
if debut1 == -1: |
| 273 |
debut = debut2 |
| 274 |
elif debut2 == -1: |
| 275 |
debut = debut1 |
| 276 |
else: |
| 277 |
debut = min(debut1, debut2) |
| 278 |
if debut == -1: |
| 279 |
reste.append(chaine[fin:]) |
| 280 |
break |
| 281 |
caractere = chaine[debut] |
| 282 |
ne. |
| 283 |
if debut: |
| 284 |
caractere_precedent = chaine[debut - 1] |
| 285 |
if caractere == "'" and (caractere_precedent.isalnum() or caractere_precedent in "_'"): |
| 286 |
e f |
| 287 |
position += 1 |
| 288 |
continue |
| 289 |
" |
| 290 |
if chaine[debut:].startswith(3*caractere): |
| 291 |
mode = 3*caractere |
| 292 |
else: |
| 293 |
mode = caractere |
| 294 |
reste.append(chaine[fin:debut]) |
| 295 |
position = debut + len(mode) |
| 296 |
|
| 297 |
else: |
| 298 |
. |
| 299 |
fin = chaine.find(mode, position) |
| 300 |
caractere_precedent = chaine[fin - 1] |
| 301 |
e. |
| 302 |
if caractere_precedent == '\\': |
| 303 |
"\" |
| 304 |
se |
| 305 |
|
| 306 |
|
| 307 |
count = 0 |
| 308 |
for car in reversed(chaine[:fin]): |
| 309 |
if car != '\\': |
| 310 |
break |
| 311 |
count += 1 |
| 312 |
if count%2: |
| 313 |
|
| 314 |
. |
| 315 |
position += 1 |
| 316 |
continue |
| 317 |
if fin == -1: |
| 318 |
. |
| 319 |
print("Warning: guillemets manquants dans %s" % repr(chaine)) |
| 320 |
reste[-1] += chaine[debut:] |
| 321 |
break |
| 322 |
position = fin = fin + len(mode) |
| 323 |
chaines.append(chaine[debut:fin]) |
| 324 |
mode = None |
| 325 |
else: |
| 326 |
raise SyntaxError('Error while scanning %s' % repr(chaine)) |
| 327 |
return '<@>'.join(reste), chaines |
| 328 |
|
| 329 |
|
| 330 |
def injecter_chaines(chaine, sous_chaines): |
| 331 |
for valeur in sous_chaines: |
| 332 |
chaine = chaine.replace('<@>', valeur, 1) |
| 333 |
assert '<@>' not in chaine |
| 334 |
return chaine.replace('@@', '@') |
| 335 |
|
| 336 |
|
| 337 |
def traduire_formule(formule='', fonctions=(), OOo=True, LaTeX=True, |
| 338 |
simpify=False, verbose=None, mots_cles=tuple(keyword.kwlist)): |
| 339 |
|
| 340 |
ées |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
<@> |
| 345 |
"]) |
| 346 |
|
| 347 |
ées |
| 348 |
|
| 349 |
|
| 350 |
formule, chaines = extraire_chaines(formule) |
| 351 |
|
| 352 |
le. |
| 353 |
formule = _convertir_separateur_decimal(formule) |
| 354 |
|
| 355 |
formule = _simplifier(formule) |
| 356 |
|
| 357 |
|
| 358 |
if verbose: |
| 359 |
print('0', formule) |
| 360 |
|
| 361 |
: |
| 362 |
formule = formule.replace("^", "**").replace('²',"**2").replace('³',"**3") |
| 363 |
formule = formule.replace('\u2074',"**4").replace('\u2075',"**5").replace('\u2076',"**6") |
| 364 |
formule = formule.replace('\u2077',"**7").replace('\u2078',"**8").replace('\u2079',"**9") |
| 365 |
|
| 366 |
. |
| 367 |
|
| 368 |
formule = formule.replace('\u2013', "-").replace('\u2212', "-") |
| 369 |
|
| 370 |
formule = formule.replace("\u00D7", "*").replace("\u00F7", "/") |
| 371 |
|
| 372 |
|
| 373 |
ion |
| 374 |
def to_frac(reg): |
| 375 |
p_entiere, p_decimale, periode = reg.groups() |
| 376 |
chaine = '((' + p_entiere.lstrip('0') + p_decimale |
| 377 |
chaine += '+' + (periode.lstrip('0') or '0') + '/' + len(periode)*'9' |
| 378 |
chaine += ')/1' + len(p_decimale)*'0' + ')' |
| 379 |
return chaine |
| 380 |
formule = re.sub(r"(\d+)[.,](\d*)\[(\d+)\]", to_frac, formule) |
| 381 |
|
| 382 |
0 |
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
if LaTeX: |
| 387 |
formule = formule.replace("\\%", "/100 ") |
| 388 |
formule = formule.replace("%", "/100 ") |
| 389 |
formule = _simplifier(formule) |
| 390 |
formule = formule.replace(" mod ", "%").replace(" modulo ", "%") |
| 391 |
formule = formule.replace(")mod ", ")%").replace(")modulo ", ")%") |
| 392 |
formule = formule.replace("}mod ", "}%").replace("}modulo ", "}%") |
| 393 |
|
| 394 |
) |
| 395 |
formule = formule.replace("+)", ",'+')").replace("-)", ",'-')") |
| 396 |
|
| 397 |
s |
| 398 |
formule = formule.replace('°', '*pi/180') |
| 399 |
|
| 400 |
if OOo: |
| 401 |
|
| 402 |
. |
| 403 |
deb = formule.find("matrix{") |
| 404 |
while deb != -1: |
| 405 |
matrice, reste = _arguments_latex(formule[deb + 6:], 1) |
| 406 |
matrice = 'mat([[' + matrice[1:-1].replace(r'##', '],[').replace('#', ',') + ']])' |
| 407 |
formule = formule[:deb] + matrice + reste |
| 408 |
deb = formule.find("matrix{", deb) |
| 409 |
|
| 410 |
|
| 411 |
. |
| 412 |
if LaTeX: |
| 413 |
|
| 414 |
. |
| 415 |
for substr in (r"matrix", |
| 416 |
r"pmatrix", |
| 417 |
r"bmatrix", |
| 418 |
r"vmatrix", |
| 419 |
r"Vmatrix", |
| 420 |
r"smallmatrix", |
| 421 |
): |
| 422 |
while True: |
| 423 |
deb = formule.find(r"\begin{" + substr + "}") |
| 424 |
if deb == -1: |
| 425 |
break |
| 426 |
fin = formule.find(r"\end{" + substr + "}", deb) |
| 427 |
avant = formule[:deb] |
| 428 |
coeur = formule[deb + len(substr) + 8:fin].replace('\n', '').rstrip('\\') |
| 429 |
apres = formule[fin + len(substr) + 6:] |
| 430 |
coeur = 'mat([[' + coeur.replace(r'\\', '],[').replace('&', ',') + ']])' |
| 431 |
formule = avant + coeur + apres |
| 432 |
|
| 433 |
for pattern, repl in dictionnaire_latex_commandes.items(): |
| 434 |
formule = re.sub("\\\\" + pattern + "(?![A-Za-z])", repl, formule) |
| 435 |
for substr, repl in dictionnaire_latex_special.items(): |
| 436 |
formule = formule.replace(substr, repl) |
| 437 |
formule = _simplifier(formule) |
| 438 |
|
| 439 |
|
| 440 |
formule = _convertir_latex_frac(formule) |
| 441 |
|
| 442 |
formule = formule.replace("{", "(").replace("}", ")") |
| 443 |
|
| 444 |
: |
| 445 |
|
| 446 |
formule = regsub(r'(?<!mat\()' + MATRICE, formule, (lambda s: 'mat(%s)' % s)) |
| 447 |
|
| 448 |
if OOo: |
| 449 |
|
| 450 |
formule = formule.replace("{", "(").replace("}", ")") |
| 451 |
formule = regsub("[ ]?(left|right)[])([]", formule, lambda s: s[-1]) |
| 452 |
. |
| •453 |
formule = regsub(r"\Wtimes\W", formule, lambda s: (s[0] + '*' + s[-1]).strip()) |
| 454 |
formule = regsub(r"\Wover\W", formule, lambda s: (s[0] + '/' + s[-1]).strip()) |
| 455 |
formule = regsub(r"\Wsup\W", formule, lambda s: (s[0] + '**' + s[-1]).strip()) |
| 456 |
formule = formule.replace('infinity', 'oo') |
| 457 |
|
| 458 |
. |
| 459 |
s |
| 460 |
e |
| 461 |
|
| 462 |
formule = regsub('[|][^|]+[|]', formule, (lambda s: 'abs(%s)' % s[1:-1])) |
| 463 |
|
| 464 |
formule = _ajouter_mult_manquants(formule, fonctions = fonctions, verbose = verbose, mots_cles = mots_cles) |
| 465 |
|
| 466 |
if verbose: |
| 467 |
print('5', formule) |
| 468 |
|
| 469 |
|
| •470 |
formule = regsub(r"\w+[!]", formule, (lambda s: 'factoriel(%s)' % s[:-1])) |
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
formule = regsub("[(]%s[ ]+%s[)]" % (NBR, NBR), formule, |
| 475 |
lambda s: 'binomial(%s)' % ",".join(s[1:-1].split())) |
| 476 |
|
| 477 |
if verbose: |
| 478 |
print('6', formule) |
| 479 |
|
| 480 |
|
| 481 |
def prime2derivee(s): |
| 482 |
n = s.count("'") |
| 483 |
return n*"derivee(" + s.rstrip("'") + n*")" |
| 484 |
|
| 485 |
formule = regsub(VAR + "[']+", formule, prime2derivee) |
| 486 |
|
| 487 |
formule = formule.replace("`", "'") |
| 488 |
|
| 489 |
if verbose: |
| 490 |
print('7', formule) |
| 491 |
|
| 492 |
if simpify: |
| 493 |
def transformer(chaine): |
| 494 |
if "." in chaine: |
| 495 |
return "__decimal__('" + chaine + "')" |
| 496 |
else: |
| 497 |
return "__sympify__(" + chaine + ")" |
| 498 |
formule = regsub(NBR, formule, transformer) |
| 499 |
|
| 500 |
formule = injecter_chaines(formule, chaines) |
| 501 |
|
| 502 |
if verbose is not False: |
| 503 |
debug(formule, "[formule transformee]") |
| 504 |
|
| 505 |
return formule |
| 506 |
|
| 507 |
|
| 508 |
def simplifier_ecriture(formule): |
| 509 |
formule = formule.replace('**', '^') |
| 510 |
formule = formule.replace('*(', '(') |
| 511 |
formule = formule.replace(')*', ')') |
| 512 |
formule = re.sub(r'[*](?![-+.0-9])', ' ', formule) |
| 513 |
return formule |
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
s |
| 518 |
|
| 519 |
|
| 520 |
s |
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
s |
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
def _fast_closing_bracket_search(string, start=0): |
| 535 |
"""Recherche rudimentaire de la parenthèse fermante correspondante. |
| 536 |
|
| 537 |
Les parenthèses imbriquées sont gérées, mais pas la détection des chaînes de |
| 538 |
caractères qui peuvent fausser les résultats. |
| 539 |
Tant que cette fonction est appliquée à des expressions mathématiques, |
| 540 |
cela ne pose pas problème. |
| 541 |
|
| 542 |
La recherche commence à partir de la position `start`, qui doit correspondre |
| 543 |
à une parenthèse ouvrante dans la chaîne. |
| 544 |
|
| 545 |
Retourne la position de la parenthèse fermante. |
| 546 |
""" |
| 547 |
ée |
| 548 |
k = start + 1 |
| 549 |
s. |
| 550 |
level = 1 |
| 551 |
while True: |
| 552 |
i = string.find('(', k) |
| 553 |
j = string.find(')', k) |
| 554 |
if i == j == -1: |
| 555 |
. |
| 556 |
raise ValueError("No matching parenthesis, or string doesn't start with `(`.") |
| 557 |
elif i < j and i != -1: |
| 558 |
(`. |
| 559 |
level += 1 |
| 560 |
k = i + 1 |
| 561 |
else: |
| 562 |
)`. |
| 563 |
level -= 1 |
| 564 |
k = j + 1 |
| 565 |
if level == 0: |
| 566 |
return k |
| 567 |
|
| 568 |
|
| 569 |
def _fast_opening_bracket_search(string): |
| 570 |
"""Recherche rudimentaire de la parenthèse ouvrante correspondante. |
| 571 |
|
| 572 |
Puisqu'on cherche la parenthèse ouvrante, la recherche s'effectue donc |
| 573 |
de droite à gauche. |
| 574 |
|
| 575 |
Les parenthèses imbriquées sont gérées, mais pas la détection des chaînes de |
| 576 |
caractères qui peuvent fausser les résultats. |
| 577 |
Tant que cette fonction est appliquée à des expressions mathématiques, |
| 578 |
cela ne pose pas problème. |
| 579 |
|
| 580 |
La chaîne doit se terminer par une parenthèse fermante. |
| 581 |
|
| 582 |
Retourne la position de la parenthèse ouvrante. |
| 583 |
""" |
| 584 |
ée |
| 585 |
k = -1 |
| 586 |
s. |
| 587 |
level = 1 |
| 588 |
while True: |
| 589 |
i = string.rfind('(', None, k) |
| 590 |
j = string.rfind(')', None, k) |
| 591 |
if i == j == -1: |
| 592 |
. |
| 593 |
raise ValueError("No matching parenthesis, or string doesn't end with `)`.") |
| 594 |
elif i > j: |
| 595 |
(`. |
| 596 |
level -= 1 |
| 597 |
k = i |
| 598 |
else: |
| 599 |
)`. |
| 600 |
level += 1 |
| 601 |
k = j |
| 602 |
if level == 0: |
| 603 |
return k |
| 604 |
|
| 605 |
|
| 606 |
def _strip_parenthesis(string): |
| 607 |
"""Supprime les parenthèses autour de l'expression, si elles correspondent.""" |
| 608 |
while string and string[0] == '(': |
| 609 |
if _fast_closing_bracket_search(string) == len(string): |
| 610 |
string = string[1:-1] |
| 611 |
else: |
| 612 |
break |
| 613 |
return string |
| 614 |
|
| 615 |
|
| 616 |
def _rechercher_numerateur(chaine): |
| 617 |
"""Part de la fin de la chaîne, et remonte la chaîne pour chercher |
| 618 |
le plus grand groupe possible pouvant correspondre à un numérateur. |
| 619 |
|
| 620 |
Retourne la position du début du numérateur dans la chaîne. |
| 621 |
|
| 622 |
La chaîne doit être préparée au préalable. En particulier, l'opérateur utilisé |
| 623 |
pour les puissances est `^`, et non `**`, et les espaces autour des opérateurs |
| 624 |
/ et ^ sont supprimés. |
| 625 |
""" |
| 626 |
if not chaine: |
| 627 |
return |
| 628 |
fonctions = ('cos', 'sin', 'tan', 'ln', 'log', 'exp', 'sqrt') |
| 629 |
if chaine[-1] == ')': |
| 630 |
try: |
| 631 |
deb = _fast_opening_bracket_search(chaine) |
| 632 |
tion |
| 633 |
, |
| 634 |
. |
| 635 |
for fonction in fonctions: |
| 636 |
if chaine.endswith(fonction, 0, deb): |
| 637 |
deb -= len(fonction) |
| 638 |
except ValueError: |
| 639 |
. |
| 640 |
return |
| 641 |
else: |
| 642 |
es |
| 643 |
ées. |
| 644 |
m = re.search('(%s|@)$' % NBR_OR_VAR, chaine) |
| 645 |
if m is None: |
| 646 |
ur |
| 647 |
return |
| 648 |
deb = m.start() |
| 649 |
|
| 650 |
. |
| 651 |
if deb != 0 and chaine[deb - 1] == '^': |
| 652 |
deb = _rechercher_numerateur(chaine[:deb - 1]) |
| 653 |
elif deb > 1 and chaine[deb - 2:deb] == '^-': |
| 654 |
deb = _rechercher_numerateur(chaine[:deb - 2]) |
| 655 |
return deb |
| 656 |
|
| 657 |
|
| 658 |
def _rechercher_denominateur(chaine): |
| 659 |
"""Part de la fin de la chaîne, et remonte la chaîne pour chercher |
| 660 |
le plus grand groupe possible pouvant correspondre à un numérateur. |
| 661 |
|
| 662 |
Retourne la position du début du numérateur dans la chaîne. |
| 663 |
|
| 664 |
La chaîne doit être préparée au préalable. En particulier, l'opérateur utilisé |
| 665 |
pour les puissances est `^`, et non `**`, et les espaces autour des opérateurs |
| 666 |
/ et ^ sont supprimés. |
| 667 |
""" |
| 668 |
if not chaine: |
| 669 |
return |
| 670 |
fonctions = ('cos', 'sin', 'tan', 'ln', 'log', 'exp', 'sqrt') |
| 671 |
er |
| 672 |
. |
| 673 |
fin = 0 |
| 674 |
for fonction in fonctions: |
| 675 |
if chaine.startswith(fonction): |
| 676 |
fin += len(fonction) |
| 677 |
if chaine[fin] == '(': |
| 678 |
try: |
| 679 |
fin += _fast_closing_bracket_search(chaine[fin:]) |
| 680 |
except ValueError: |
| 681 |
. |
| 682 |
return |
| 683 |
else: |
| 684 |
m = re.search('(%s)' % NBR_SIGNE_OR_VAR, chaine[fin:]) |
| 685 |
if m is None: |
| 686 |
ur |
| 687 |
return |
| 688 |
fin += m.end() |
| 689 |
|
| 690 |
. |
| 691 |
if fin < len(chaine) and chaine[fin] == '^': |
| 692 |
fin += _rechercher_denominateur(chaine[fin + 1:]) + 1 |
| 693 |
elif chaine[fin:fin + 2] == '^-': |
| 694 |
fin += _rechercher_denominateur(chaine[fin + 2:]) + 2 |
| 695 |
return fin |
| 696 |
|
| 697 |
|
| 698 |
def _convertir_en_latex(chaine): |
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
chaine = chaine.replace("**", "^") |
| 704 |
|
| 705 |
|
| 706 |
def simpl(m): |
| 707 |
return '-' if m.group(0).count('-')%2 else '+' |
| 708 |
chaine = re.sub('[-+]{2,}', simpl, chaine) |
| 709 |
if chaine != '+': |
| 710 |
chaine = chaine.lstrip('+') |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
|
| 716 |
n |
| 717 |
es. |
| 718 |
chaine = re.sub(r'[ ]+', ' ', chaine) |
| 719 |
chaine = re.sub(r'[ ]?([/^()+*-])[ ]?', (lambda m: m.group(1)), chaine) |
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
, |
| 725 |
|
| 726 |
securite = 1000 |
| 727 |
while '/' in chaine: |
| 728 |
. |
| 729 |
fractions = [] |
| 730 |
while '/' in chaine: |
| 731 |
securite -= 1 |
| 732 |
if securite < 0: |
| 733 |
raise RuntimeError("Boucle probablement infinie.") |
| 734 |
i = chaine.find("/") |
| 735 |
n |
| 736 |
deb = _rechercher_numerateur(chaine[:i]) |
| 737 |
if deb is None: |
| 738 |
if param.debug: |
| 739 |
warning("Expression incorrecte: numerateur introuvable.") |
| 740 |
return chaine |
| 741 |
|
| 742 |
_fin = _rechercher_denominateur(chaine[i + 1:]) |
| 743 |
if _fin is None: |
| 744 |
if param.debug: |
| 745 |
warning("Expression incorrecte: denominateur introuvable.") |
| 746 |
return chaine |
| 747 |
fin = i + 1 + _fin |
| 748 |
|
| 749 |
. |
| 750 |
numerateur = _strip_parenthesis(chaine[deb:i]) |
| 751 |
denominateur = _strip_parenthesis(chaine[i + 1:fin]) |
| 752 |
fractions.append(r'\frac{%s}{%s}' % (numerateur, denominateur)) |
| 753 |
, |
| 754 |
|
| 755 |
|
| 756 |
r. |
| 757 |
s |
| 758 |
|
| 759 |
chaine = chaine[:deb] + '@' + chaine[fin:] |
| 760 |
|
| 761 |
/` |
| 762 |
ion. |
| 763 |
). |
| 764 |
s |
| 765 |
|
| 766 |
te |
| 767 |
|
| 768 |
on, |
| 769 |
. |
| 770 |
, |
| 771 |
n |
| 772 |
ur |
| 773 |
son |
| 774 |
é. |
| 775 |
|
| 776 |
for fraction in reversed(fractions): |
| 777 |
chaine = rreplace(chaine, '@', fraction, 1) |
| 778 |
assert '@' not in chaine |
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
chaine = re.sub(r"(?<!\w|\\)(pi|e|sin|cos|tan|ln|log|exp|sqrt)(?!\w)", lambda m:"\\" + m.group(), chaine) |
| 784 |
chaine = re.sub(r"(?<!\w|\\)oo(?!\w)", lambda m:"\\infty", chaine) |
| 785 |
for func in ('sqrt', '^'): |
| 786 |
i = 0 |
| 787 |
while True: |
| 788 |
i = chaine.find(func + '(', i) |
| 789 |
if i == -1: |
| 790 |
break |
| 791 |
i += len(func) |
| 792 |
j = _fast_closing_bracket_search(chaine, start=i) |
| 793 |
if j is None: |
| 794 |
if param.debug: |
| 795 |
warning("Expression incorrecte: %s." % chaine) |
| 796 |
return chaine |
| 797 |
chaine = chaine[:i] + '{' + chaine[i + 1:j - 1] + '}' + chaine[j:] |
| 798 |
|
| 799 |
chaine = re.sub(r'\*' + NBR_SIGNE, lambda m: r'\times ' + m.group()[1:], chaine) |
| 800 |
chaine = chaine.replace("*", " ") |
| 801 |
|
| 802 |
|
| 803 |
chaine = re.sub(r'(?<=\^)' + NBR_SIGNE, (lambda m: '{' + m.group() + '}'), chaine) |
| 804 |
|
| 805 |
if chaine.startswith(r'\infty'): |
| 806 |
chaine = '+' + chaine |
| 807 |
|
| 808 |
return _strip_parenthesis(chaine) |
| 809 |
|
| 810 |
|
| 811 |
def convertir_en_latex(chaine, mode='$'): |
| 812 |
"""Convertit une chaine représentant un calcul en Python, en du code LaTeX. |
| 813 |
|
| 814 |
modes actuels: '$', None |
| 815 |
|
| 816 |
L'intérêt de ne pas passer par sympy, c'est que le code n'a pas besoin |
| 817 |
d'être évalué. Si le code était évalué par sympy, cela pourrait modifier |
| 818 |
l'ordre des termes (par exemple, transformer `2-x` en `-x+2`). |
| 819 |
""" |
| 820 |
chaine = _convertir_en_latex(chaine) |
| 821 |
if mode == '$' and chaine: |
| 822 |
chaine = "$" + chaine + "$" |
| 823 |
return chaine |
| 824 |
|
| 825 |
|
| 826 |
def latex2mathtext(chaine): |
| 827 |
"""Convertit la chaîne pour qu'elle puisse être affichée par mathtext. |
| 828 |
|
| 829 |
Matplotlib offre 2 possibilités pour l'affichage de chaînes LaTeX : |
| 830 |
|
| 831 |
* soit utiliser une installation LaTeX existante, |
| 832 |
* soit utiliser son propre moteur de rendu, mathtext. |
| 833 |
|
| 834 |
Le rendu de matplotlib.mathtext est loin d'avoir la qualité du vrai LaTeX, |
| 835 |
mais il ne nécessite pas d'avoir LaTeX installé, il est bien plus rapide, |
| 836 |
et il permet l'export au format vectoriel (matplotlib utilise dvi2png sinon). |
| 837 |
|
| 838 |
C'est donc le format utilisé par défaut. |
| 839 |
""" |
| 840 |
if '$' in chaine: |
| 841 |
if chaine.startswith(r"$\begin{bmatrix}"): |
| 842 |
chaine = chaine.replace(r"\begin{bmatrix}", r'\left({') |
| 843 |
chaine = chaine.replace(r"\end{bmatrix}", r'}\right)') |
| 844 |
chaine = chaine.replace(r"&", r'\,') |
| 845 |
if r'\left' in chaine: |
| 846 |
if matplotlib.__version__ < '1.5': |
| 847 |
chaine = chaine.replace(r'\left\{', r'\left{') |
| 848 |
chaine = chaine.replace(r'\right\}', r'\right}') |
| 849 |
|
| 850 |
|
| 851 |
te |
| 852 |
. |
| 853 |
|
| 854 |
if r'\left]' in chaine or r'\right[' in chaine: |
| 855 |
chaine = chaine.replace(r'\left]', ']').replace(r'\left[', '[').replace(r'\right]', ']').replace(r'\right[', '[') |
| 856 |
|
| 857 |
return chaine |
| 858 |
|
| 859 |
|
| 860 |
def mathtext_parser(txt): |
| 861 |
return _mathtext_raw_parser(latex2mathtext(txt)) |
| 862 |
|
| 863 |
|
| 864 |
def tex_dollars(txt): |
| 865 |
"Rajoute des $ si l'expression LaTeX ainsi obtenue est correcte." |
| 866 |
try: |
| 867 |
mathtext_parser('$' + txt + '$') |
| 868 |
return '$' + txt + '$' |
| 869 |
except Exception: |
| 870 |
return txt |
| 871 |
|
| 872 |
|