| 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 re, types |
| 25 |
import numpy |
| 26 |
|
| 27 |
import sympy |
| 28 |
from sympy import Symbol, Basic, Float, sympify, nsimplify, S, Matrix |
| 29 |
|
| 30 |
from .intervalles import Ensemble |
| 31 |
from .printers import custom_str, custom_latex |
| 32 |
from .custom_functions import frac |
| 33 |
from .custom_objects import Temps, Fonction, ProduitEntiers, Decim |
| 34 |
from . import sympy_functions |
| 35 |
from ..mathlib import end_user_functions |
| 36 |
from ..pylib import print_error, split_around_parenthesis, securite |
| 37 |
from .parsers import simplifier_ecriture, NBR, traduire_formule, NBR_FLOTTANT, \ |
| 38 |
extraire_chaines, injecter_chaines |
| 39 |
from .. import param |
| 40 |
|
| 41 |
|
| 42 |
class LocalDict(dict): |
| 43 |
def __init__(self, defaut=None): |
| 44 |
dict.__init__(self) |
| 45 |
self.defaut = (defaut if defaut is not None else {}) |
| 46 |
self.update(self.defaut) |
| 47 |
|
| 48 |
|
| 49 |
def __missing__(self, key): |
| 50 |
|
| 51 |
if key.startswith('_'): |
| 52 |
if key[1:].isnumeric(): |
| 53 |
return self['ans'](int(key[1:])) |
| 54 |
else: |
| 55 |
if key == len(key)*'_': |
| 56 |
return self['ans'](-len(key)) |
| 57 |
if key in sympy.__dict__: |
| 58 |
return sympy.__dict__[key] |
| 59 |
else: |
| 60 |
return Symbol(key) |
| 61 |
|
| 62 |
def __setitem__(self, name, value): |
| 63 |
de. |
| 64 |
_). |
| 65 |
if (name in self.defaut or (name.startswith('_') and name[1:].isalnum())) and name != '__builtins__': |
| 66 |
raise NameError("%s est un nom reserve" %name) |
| 67 |
dict.__setitem__(self, name, value) |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
class Interprete(object): |
| 73 |
"""Un interprêteur de commandes mathématiques, avec gestion des sessions. |
| 74 |
|
| 75 |
Les options sont les suivantes:: |
| 76 |
|
| 77 |
* `calcul_exact`: mode calcul exact ou calcul approché |
| 78 |
* `ecriture_scientifique`: affiche les résultats en écriture scientifique |
| 79 |
(essentiellement pertinent pour des résultats numériques) |
| 80 |
* `forme_algebrique`: affiche les nombres complexes sous la forme a+ib |
| 81 |
* `simplifier_ecriture_resultat`: Écrire le résultat sous une forme plus |
| 82 |
agréable à lire (suppression des '*' dans '2*x', etc.) |
| 83 |
* `separateur_decimal`: point ou virgule (',' par défaut) |
| 84 |
* `formatage_OOo`: convertir et interpréter les formules OpenOffice |
| 85 |
ou LibreOffice |
| 86 |
* `formatage_LaTeX`: convertir et interpréter les formules LaTeX |
| 87 |
* `ecriture_scientifique_decimales`: nombre de décimales affichées |
| 88 |
en mode écriture scientifique. |
| 89 |
* `precision_calcul`: précision utilisée en interne pour les calculs |
| 90 |
approchés (nombre de chiffres). |
| 91 |
* `precision_affichage`: nombre de chiffres affichés pour les résultats |
| 92 |
approchés |
| 93 |
* `simpify`: convertir automatiquement les expressions au format sympy |
| 94 |
* `verbose`: afficher le détail des transformations effectuées |
| 95 |
* `appliquer_au_resultat`: une opération à appliquer éventuellement |
| 96 |
au résultat. La résultat est représenté par un underscore : _. |
| 97 |
Exemple : 'factoriser(_)'. |
| 98 |
* `ensemble`: 'R' ou 'C' (utilisé pour la résolution des équations). |
| 99 |
""" |
| 100 |
def __init__(self, calcul_exact=True, |
| 101 |
ecriture_scientifique=False, |
| 102 |
forme_algebrique=True, |
| 103 |
simplifier_ecriture_resultat=True, |
| 104 |
separateur_decimal=',', |
| 105 |
formatage_OOo=True, |
| 106 |
formatage_LaTeX=True, |
| 107 |
ecriture_scientifique_decimales=2, |
| 108 |
precision_calcul=60, |
| 109 |
precision_affichage=18, |
| 110 |
simpify=True, |
| 111 |
verbose=None, |
| 112 |
appliquer_au_resultat=None, |
| 113 |
ensemble='R' |
| 114 |
): |
| 115 |
|
| 116 |
s). |
| 117 |
self.defaut = vars(end_user_functions).copy() |
| 118 |
self.defaut.update({ |
| 119 |
"__builtins__": {}, |
| 120 |
"Fonction": Fonction, |
| 121 |
"Matrice": Matrix, |
| 122 |
"Temps": Temps, |
| 123 |
"ProduitEntiers": ProduitEntiers, |
| 124 |
"Ensemble": Ensemble, |
| 125 |
"__sympify__": sympify, |
| 126 |
"ans": self.ans, |
| 127 |
"rep": self.ans, ) |
| 128 |
|
| 129 |
|
| 130 |
"__decimal__": self._decimal, |
| 131 |
"range": numpy.arange, |
| 132 |
"arange": numpy.arange, |
| 133 |
"frac": self._frac, |
| 134 |
"Decim": Decim, |
| 135 |
}) |
| 136 |
|
| 137 |
e, |
| 138 |
t. |
| 139 |
a_importer = ['all', 'isinstance', 'dict', 'oct', 'sorted', |
| 140 |
'list', 'iter', 'set', 'issubclass', 'getattr', |
| 141 |
'hash', 'len', 'frozenset', 'ord', 'filter', 'pow', |
| 142 |
'float', 'divmod', 'enumerate', 'zip', |
| 143 |
'hex', 'chr', 'type', 'tuple', 'reversed', 'hasattr', |
| 144 |
'delattr', 'setattr', 'str', 'int', 'any', |
| 145 |
'min', 'complex', 'bool', 'max', 'True', 'False'] |
| 146 |
|
| 147 |
for nom in a_importer: |
| 148 |
self.defaut[nom] = __builtins__[nom] |
| 149 |
|
| 150 |
s |
| 151 |
. |
| 152 |
self.vars = LocalDict(self.defaut) |
| 153 |
rs. |
| 154 |
self.vars['__local_dict__'] = self.vars |
| 155 |
self.defaut['__local_dict__'] = self.vars |
| 156 |
|
| 157 |
self.calcul_exact = calcul_exact |
| 158 |
|
| 159 |
self.ecriture_scientifique = ecriture_scientifique |
| 160 |
ue |
| 161 |
self.forme_algebrique = forme_algebrique |
| 162 |
lire |
| 163 |
|
| 164 |
self.simplifier_ecriture_resultat = simplifier_ecriture_resultat |
| 165 |
és |
| 166 |
self.separateur_decimal = separateur_decimal or param.separateur_decimal |
| 167 |
. |
| 168 |
self.formatage_OOo = formatage_OOo |
| 169 |
self.formatage_LaTeX = formatage_LaTeX |
| 170 |
self.ecriture_scientifique_decimales = ecriture_scientifique_decimales |
| 171 |
self.precision_calcul = precision_calcul |
| 172 |
self.precision_affichage = precision_affichage |
| 173 |
self.verbose = verbose |
| 174 |
self.simpify = simpify |
| 175 |
ats. |
| 176 |
self.appliquer_au_resultat = appliquer_au_resultat |
| 177 |
self.ensemble = ensemble |
| 178 |
self.latex_dernier_resultat = '' |
| 179 |
self.initialiser() |
| 180 |
|
| 181 |
def _decimal(self, nbr, prec=None): |
| 182 |
"""Convertit en fraction avec affichage décimal. |
| 183 |
""" |
| 184 |
if prec is None: |
| 185 |
prec = self.precision_calcul |
| 186 |
return Decim(nsimplify(nbr, rational=True), prec=prec) |
| 187 |
|
| 188 |
def _frac(self, arg): |
| 189 |
"""Convertit en fraction. |
| 190 |
""" |
| 191 |
return frac(arg) |
| 192 |
|
| 193 |
|
| 194 |
def initialiser(self): |
| 195 |
self.clear_state() |
| 196 |
self.derniers_resultats = [] |
| 197 |
|
| 198 |
|
| 199 |
def evaluer(self, calcul = "", calcul_exact=None): |
| 200 |
if calcul_exact is None: |
| 201 |
calcul_exact = self.calcul_exact |
| 202 |
|
| 203 |
self.warning = "" |
| 204 |
s. |
| 205 |
ns. |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
parentheses = "({[", ")}]" |
| 210 |
for i in range(3): |
| 211 |
difference = calcul.count(parentheses[0][i])-calcul.count(parentheses[1][i]) |
| 212 |
if difference > 0: |
| 213 |
calcul += difference*parentheses[1][i] |
| 214 |
self.warning += " Attention, il manque des parenthèses \"" + parentheses[1][i] + "\"." |
| 215 |
elif difference < 0: |
| 216 |
self.warning += " Attention, il y a des parenthèses \"" + parentheses[1][i] + "\" superflues." |
| 217 |
if calcul.endswith(abs(difference)*parentheses[1][i]): |
| 218 |
calcul = calcul[:difference] |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
if self.verbose: |
| 224 |
print("Traitement ({[]}) : ", calcul) |
| 225 |
|
| 226 |
if calcul and calcul[0] in "><!=^*/%+": |
| 227 |
calcul = "_" + calcul |
| 228 |
|
| 229 |
if self.verbose: |
| 230 |
print("Traitement ><!=^*/%+ : ", calcul) |
| 231 |
|
| 232 |
if self.formatage_LaTeX and calcul.rstrip().endswith("\\approx"): |
| 233 |
calcul = calcul.rstrip()[:-7] + ">>evalf" |
| 234 |
|
| 235 |
if ">>" in calcul: |
| 236 |
liste = calcul.split(">>") |
| 237 |
calcul = liste[0] |
| 238 |
for s in liste[1:]: |
| 239 |
calcul = s + "(" + calcul + ")" |
| 240 |
|
| 241 |
if self.verbose: |
| 242 |
print("Traitement >> : ", calcul) |
| 243 |
|
| 244 |
if calcul.startswith('?'): |
| 245 |
calcul = 'aide(%s)' %calcul[1:] |
| 246 |
elif calcul.endswith('?'): |
| 247 |
calcul = 'aide(%s)' %calcul[:-1] |
| 248 |
|
| 249 |
try: |
| 250 |
param.calcul_approche = not calcul_exact |
| 251 |
es |
| 252 |
self._executer(calcul) |
| 253 |
finally: |
| 254 |
param.calcul_approche = False |
| 255 |
|
| 256 |
if self.appliquer_au_resultat is not None: |
| 257 |
self._executer(self.appliquer_au_resultat) |
| 258 |
|
| 259 |
dernier_resultat = self.vars["_"] |
| 260 |
|
| 261 |
self.derniers_resultats.append(dernier_resultat) |
| 262 |
|
| 263 |
if not calcul_exact: |
| 264 |
return self._formater(sympy_functions.evalf(dernier_resultat, self.precision_calcul)) |
| 265 |
return self._formater(dernier_resultat) |
| 266 |
|
| 267 |
|
| 268 |
def _formater(self, valeur): |
| 269 |
if isinstance(valeur, Basic): |
| 270 |
valeur = valeur.subs(Float(1), S.One) |
| 271 |
|
| 272 |
parametres = {'decimales': self.precision_affichage, |
| 273 |
'mode_scientifique': self.ecriture_scientifique, |
| 274 |
'decimales_sci': self.ecriture_scientifique_decimales, |
| 275 |
} |
| 276 |
resultat = custom_str(valeur, **parametres) |
| 277 |
if valeur is None: |
| 278 |
latex = "" |
| 279 |
else: |
| 280 |
try: |
| 281 |
latex = custom_latex(valeur, **parametres) |
| 282 |
except Exception: |
| 283 |
print_error() |
| 284 |
latex = '' |
| 285 |
|
| 286 |
|
| 287 |
if self.separateur_decimal != '.' and not isinstance(valeur, str): |
| 288 |
ur : |
| 289 |
. |
| 290 |
resultat, sous_chaines_resultat = extraire_chaines(resultat) |
| 291 |
latex, sous_chaines_latex = extraire_chaines(latex) |
| 292 |
resultat = re.sub(r"[ ]*[,;][ ]*", ' ; ', resultat) |
| 293 |
. |
| 294 |
latex = re.sub(r"(?<![\\ ])[ ]*,[ ]*", ';', latex) |
| 295 |
def sep(m): |
| 296 |
return m.group().replace('.', self.separateur_decimal) |
| 297 |
resultat = re.sub(NBR, sep, resultat) |
| 298 |
latex = re.sub(NBR, sep, latex) |
| 299 |
in. |
| 300 |
resultat = injecter_chaines(resultat, sous_chaines_resultat) |
| 301 |
latex = injecter_chaines(latex, sous_chaines_latex) |
| 302 |
|
| 303 |
if isinstance(valeur, str): |
| 304 |
latex = '\u201C%s\u201D' %valeur |
| 305 |
|
| 306 |
self.latex_dernier_resultat = latex |
| 307 |
if self.simplifier_ecriture_resultat: |
| 308 |
resultat = simplifier_ecriture(resultat) |
| 309 |
return resultat, latex |
| 310 |
|
| 311 |
|
| 312 |
def _traduire(self, formule): |
| 313 |
|
| 314 |
if self.verbose or (self.verbose is None and param.debug): |
| 315 |
print('Avant traduction: %s' % repr(formule)) |
| 316 |
. |
| 317 |
formule = traduire_formule(formule, fonctions=self.vars, |
| 318 |
OOo=self.formatage_OOo, |
| 319 |
LaTeX=self.formatage_LaTeX, |
| 320 |
simpify=self.simpify, |
| 321 |
verbose=self.verbose, |
| 322 |
) |
| 323 |
if self.verbose or (self.verbose is None and param.debug): |
| 324 |
print('Après traduction: %s' % repr(formule)) |
| 325 |
|
| 326 |
formule = re.sub("(?<![A-Za-z0-9_])(resous|solve)[(]", "resoudre(", formule) |
| 327 |
i = formule.find("resoudre(") |
| 328 |
if i != -1: |
| 329 |
while formule.find("(et)") != -1: |
| 330 |
formule = formule.replace("(et)", "et") |
| 331 |
while formule.find("(ou)") != -1: |
| 332 |
formule = formule.replace("(ou)", "ou") |
| 333 |
formule = formule.replace("*ou*", " ou ").replace("*et*", " et ")\ |
| 334 |
.replace("*ou-", " ou -").replace("*et-", " et -")\ |
| 335 |
.replace("*ou+", " ou +").replace("*et+", " et +") |
| 336 |
deb, bloc, fin = split_around_parenthesis(formule, i) |
| 337 |
formule = ('%s("%s", local_dict=__local_dict__, ensemble=%s)%s' |
| 338 |
% (deb, bloc[1:-1], repr(self.ensemble), fin)) |
| 339 |
if self.verbose or (self.verbose is None and param.debug): |
| 340 |
print("Debugging resoudre(): ", i, formule) |
| 341 |
formule = re.sub("(?<![A-Za-z0-9_])(factor|factorise)[(]", "factoriser(", formule) |
| 342 |
i = formule.find("factoriser(") |
| 343 |
if i != -1: |
| 344 |
deb, bloc, fin = split_around_parenthesis(formule, i) |
| 345 |
formule = ('%s(%s, ensemble=%s)' |
| 346 |
% (deb, bloc[1:-1], repr(self.ensemble))) |
| 347 |
if self.verbose or (self.verbose is None and param.debug): |
| 348 |
print("Debugging factor(): ", formule) |
| 349 |
return formule |
| 350 |
|
| 351 |
|
| 352 |
def _executer(self, instruction): |
| 353 |
instruction = instruction.strip() |
| 354 |
|
| 355 |
|
| 356 |
if re.match("[^=()]+[(][^=()]+[)][ ]*=[^=]", instruction): |
| 357 |
var, val = instruction.split("=", 1) |
| 358 |
var = var.strip() |
| 359 |
i = var.find("(") |
| 360 |
nom = var[:i] |
| 361 |
variables = var[i:] |
| 362 |
instruction = nom + "=Fonction(" + variables + "," + self._traduire(val) + ")" |
| 363 |
|
| 364 |
|
| 365 |
. |
| 366 |
elif re.match(r"mat\s+\w+\s*=[^=]", instruction): |
| 367 |
var, val = instruction.split("=", 1) |
| 368 |
var = var[3:].strip() |
| 369 |
val = val.strip() |
| 370 |
|
| 371 |
if '&' in val: |
| 372 |
if r"\\" in val: |
| 373 |
|
| 374 |
matrix = [s.split('&') for s in val.split(r'\\')] |
| 375 |
else: |
| 376 |
|
| 377 |
matrix = [s.split('&') for s in val.split('\\')] |
| 378 |
elif "\\" in val: |
| 379 |
if r"\\" in val: |
| 380 |
|
| 381 |
matrix = [[s.strip()] for s in val.split(r'\\')] |
| 382 |
else: |
| 383 |
|
| 384 |
matrix = [[s.strip()] for s in val.split("\\")] |
| 385 |
else: |
| 386 |
if ";" in val: |
| 387 |
|
| 388 |
matrix = [s.split() for s in val.split(';')] |
| 389 |
else: |
| 390 |
|
| 391 |
matrix = [s.split() for s in re.split(r'\s\s+', val)] |
| 392 |
def to_str(liste): |
| 393 |
return "[%s]" % ', '.join(liste) |
| 394 |
matrix_code = to_str(to_str(line) for line in matrix) |
| 395 |
instruction = self._traduire(f"{var}=mat({matrix_code})") |
| 396 |
al |
| 397 |
else: |
| 398 |
instruction = self._traduire(instruction) |
| 399 |
|
| 400 |
e) |
| 401 |
e) |
| 402 |
vars = self.vars |
| 403 |
|
| 404 |
if securite.expression_affectable(instruction): |
| 405 |
instruction = "_=" + instruction |
| 406 |
else: |
| 407 |
vars["_"] = None |
| 408 |
|
| 409 |
if securite.keywords_interdits_presents(instruction): |
| 410 |
self.warning += ('Les mots-clefs %s sont interdits.' |
| 411 |
% ', '.join(sorted(securite.keywords_interdits))) |
| 412 |
raise RuntimeError("Mots-clefs interdits.") |
| 413 |
|
| 414 |
try: |
| 415 |
exec(instruction, vars) |
| 416 |
except NotImplementedError: |
| 417 |
print_error() |
| 418 |
vars["_"] = "?" |
| 419 |
if isinstance(vars["_"], Basic): |
| 420 |
vars["_"] = vars["_"].subs({1.0: 1, -1.0: -1}) |
| 421 |
if (self.forme_algebrique and vars["_"].is_number): |
| 422 |
try: |
| 423 |
vars["_"] = vars["_"].expand(complex=True) |
| 424 |
except NotImplementedError: |
| 425 |
print_error() |
| 426 |
|
| 427 |
def ans(self, n = -1): |
| 428 |
if n >= 0: |
| 429 |
n = int(n-1) |
| 430 |
else: |
| 431 |
n = int(n) |
| 432 |
if self.derniers_resultats: return self.derniers_resultats[n] |
| 433 |
self.warning += " Ans(): aucun calcul antérieur." |
| 434 |
return 0 |
| 435 |
|
| 436 |
def clear_state(self): |
| 437 |
self.vars.clear() |
| 438 |
self.vars.update(self.defaut) |
| 439 |
|
| 440 |
def save_state(self): |
| 441 |
def repr2(expr): |
| 442 |
if isinstance(expr, (types.BuiltinFunctionType, type, types.FunctionType)): |
| 443 |
return expr.__name__ |
| 444 |
return repr(expr).replace('\n', ' ') |
| 445 |
|
| 446 |
l = [] |
| 447 |
for k, v in self.vars.items(): |
| 448 |
if k not in self.defaut or self.defaut[k] is not v: |
| 449 |
l.append(k + ' = ' + repr2(v)) |
| 450 |
variables = '\n'.join(l) |
| 451 |
|
| 452 |
resultats = '\n '.join(repr(repr2(res)) + ',' for res in self.derniers_resultats) |
| 453 |
return '%s\n\n@derniers_resultats = [\n %s\n ]' % (variables, resultats) |
| 454 |
|
| 455 |
|
| 456 |
def load_state(self, state): |
| 457 |
def evaltry(expr): |
| 458 |
"Evalue l'expression. En cas d'erreur, intercepte l'erreur et retourne None." |
| 459 |
ne. |
| 460 |
chaine, sous_chaines = extraire_chaines(expr) |
| 461 |
chaine = re.sub(NBR_FLOTTANT, (lambda x: "Decim('%s')" % x.group()), chaine) |
| 462 |
expr = injecter_chaines(chaine, sous_chaines) |
| 463 |
|
| 464 |
try: |
| 465 |
return sympify(expr, self.vars.copy()) |
| 466 |
except Exception: |
| 467 |
print("Error: l'expression suivante n'a pu être évaluée par l'interprète: %s." %repr(expr)) |
| 468 |
print_error() |
| 469 |
|
| 470 |
self.clear_state() |
| 471 |
etat_brut, derniers_resultats = state.split('@derniers_resultats = ', 1) |
| 472 |
etat = (l.split(' = ', 1) for l in etat_brut.split('\n') if l) |
| 473 |
self.vars.update((k, evaltry(v)) for k, v in etat) |
| 474 |
liste_repr = eval(derniers_resultats, self.vars) |
| 475 |
self.derniers_resultats = [evaltry(s) for s in liste_repr] |