Debian Codegraph @

wxgeometrie/mathlib/sympy_functions.py

raw symbols SCIP
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 # version unicode
25
26 ## Cette librairie est une interface pour sympy :
27 ## Elle modifie si nécessaire le comportement de fonctions sympy.
28
29 from types import FunctionType
30 from functools import reduce
31
32 from sympy import (Basic, expand as expand_, apart, Function, Integer, factorint, Symbol,
33 diff as diff_, divisors as divisors_, cancel, together as together_,
34 limit as limit_, factor as factor_, integrate as integrate_, Sum,
35 sqrtdenest, solve as solve_, product as product_, Matrix,
36 ZeroMatrix, Identity, FunctionMatrix, Lambda, Dummy, I)
37
38 from .custom_objects import Fonction, ProduitEntiers, Decim, \
39 convert2decim
40 from .internal_functions import extract_var, poly_factor, syms
41 from .custom_functions import auto_collect, derivee
42 from ..pylib import print_error
43 from .. import param
44
45 def expand(expression, variable = None):
46 expression = expand_(expression)
47 if isinstance(expression, Basic) and expression.is_rational_function():
48 # Éviter d'appeler `apart()` pour rien, d'autant que FloatFrac() n'est
49 # pas compatible avec apart() (sympy v0.7.2).
50 num, den = expression.as_numer_denom()
51 if den.free_symbols:
52 if variable is None:
53 variable = extract_var(expression)
54 return apart(expression, variable)
55 return expression
56
57
58 def evalf(expression, precision=60):
59 """Evalue l'expression en respectant sa structure.
60
61 Par exemple, un polynôme factorisé reste factorisé après évaluation.
62
63 >>> from wxgeometrie.mathlib.sympy_functions import evalf
64 >>> from sympy import var, pi
65 >>> var('x')
66 x
67 >>> x*(x+pi)
68 x*(x + pi)
69 >>> evalf(x*(x+pi), precision=7)
70 x*(x + 3.141593)
71 >>> evalf([pi, pi + 1, pi + 2], precision=3)
72 [3.14, 4.14, 5.14]
73 """
74 if isinstance(expression, (list, tuple)):
75 return expression.__class__(evalf(val, precision) for val in expression)
76 elif isinstance(expression, dict):
77 return dict((key, evalf(val, precision)) for key, val in expression.items())
78 elif not isinstance(expression, Basic):
79 if hasattr(expression, 'evalf'):
80 return expression.evalf(precision)
81 elif hasattr(expression, '__float__'):
82 return float(expression)
83 return expression
84 elif expression.is_Atom or isinstance(expression, Function):
85 return expression.evalf(precision)
86 else:
87 return expression.func(*(evalf(arg, precision) for arg in expression.args))
88
89
90 def factor(expression, variable = None, ensemble = None, decomposer_entiers = True):
91 if isinstance(expression, (int, Integer)):
92 if decomposer_entiers:
93 return ProduitEntiers(*factorint(expression).items())
94 else:
95 return expression
96
97 elif isinstance(expression, Basic) and expression.is_polynomial():
98 if variable is None:
99 variable = extract_var(expression)
100 if variable is None:
101 # polynôme à plusieurs variables
102 return factor_(expression)
103 else:
104 try:
105 result = poly_factor(expression, variable, ensemble)
106 if any(isinstance(a, Decim) for a in expression.atoms()):
107 result = convert2decim(result)
108 return result
109 except NotImplementedError:
110 if param.debug:
111 print_error()
112 return expression
113 resultat = together_(expression)
114 if resultat.is_rational_function():
115 num, den = resultat.as_numer_denom()
116 if den != 1:
117 return factor(num, variable, ensemble, decomposer_entiers)/factor(den, variable, ensemble, decomposer_entiers)
118 else:
119 resultat = auto_collect(resultat)
120 if resultat.is_Mul:
121 produit = 1
122 for facteur in resultat.args:
123 if facteur != 1:
124 produit *= factor(facteur, variable, ensemble, decomposer_entiers)
125 return produit
126 return resultat
127
128
129 def cfactor(expression, variable = None):
130 return factor(expression, variable, ensemble = "C")
131
132
133 def series(expression, variable = None, point = 0, ordre = 5):
134 if variable is None:
135 if syms(expression):
136 variable = syms(expression)[0]
137 else:
138 variable = Symbol("x")
139 return getattr(expression, "series")(variable, point, ordre)
140
141
142 def diff(expression, variable = None, n = 1):
143 if isinstance(expression, Fonction):
144 return derivee(expression)
145 if variable is None and hasattr(expression, "atoms") and len(expression.atoms(Symbol)) == 1:
146 variable = expression.atoms(Symbol).pop()
147 return diff_(expression, variable, n)
148
149
150 def divisors(n):
151 return divisors_(int(n))
152
153
154 def limit(expression, *args):
155 args = list(args)
156 if args[-1] == "-" or args[-1] == "+":
157 dir = args.pop()
158 else:
159 dir = None
160 if len(args) == 1 and len(expression.atoms(Symbol)) == 1:
161 args = [expression.atoms(Symbol).pop()] + args
162 if dir is None:
163 limite_gauche = limit_(expression, args[0], args[1], "-")
164 limite_droite = limit_(expression, args[0], args[1], "+")
165 if limite_gauche is limite_droite:
166 return limite_gauche
167 return limite_gauche, limite_droite
168 else:
169 return limit_(expression, args[0], args[1], dir)
170
171 def integrate(expression, *args):
172 if len(args) == 3 and isinstance(args[0], Symbol) \
173 and not isinstance(args[1], Symbol) \
174 and isinstance(args[1], Basic) \
175 and not isinstance(args[2], Symbol) \
176 and isinstance(args[2], Basic):
177 return integrate_(expression, (args[0], args[1], args[2]))
178 elif len(args) == 2 and len(syms(expression)) <= 1 \
179 and not isinstance(args[0], Symbol) \
180 and isinstance(args[0], Basic) \
181 and not isinstance(args[1], Symbol) \
182 and isinstance(args[1], Basic):
183 if syms(expression):
184 return integrate_(expression, (syms(expression)[0], args[0], args[1]))
185 else:
186 return integrate_(expression, (Symbol("x"), args[0], args[1]))
187 return integrate_(expression, *args)
188
189 def sum(expression, *args):
190 if len(args) == 3 and isinstance(args[0], Symbol) \
191 and not isinstance(args[1], Symbol) \
192 and isinstance(args[1], Basic) \
193 and not isinstance(args[2], Symbol) \
194 and isinstance(args[2], Basic):
195 args = (args[0], args[1], args[2])
196 elif len(args) == 2 and len(syms(expression)) <= 1 \
197 and not isinstance(args[0], Symbol) \
198 and isinstance(args[0], Basic) \
199 and not isinstance(args[1], Symbol) \
200 and isinstance(args[1], Basic):
201 if syms(expression):
202 args = (syms(expression)[0], args[0], args[1])
203 else:
204 args = (Symbol("x"), args[0], args[1])
205 return Sum(expression, args).doit()
206
207 def product(expression,
208 *args):
209 if len(args) == 3 and isinstance(args[0], Symbol) \
210 and not isinstance(args[1], Symbol) \
211 and isinstance(args[1], Basic) \
212 and not isinstance(args[2], Symbol) \
213 and isinstance(args[2], Basic):
214 return product_(expression, (args[0], args[1], args[2]))
215 elif len(args) == 2 and len(syms(expression)) <= 1 \
216 and not isinstance(args[0], Symbol) \
217 and isinstance(args[0], Basic) \
218 and not isinstance(args[1], Symbol) \
219 and isinstance(args[1], Basic):
220 if syms(expression):
221 return product_(expression, (syms(expression)[0], args[0], args[1]))
222 else:
223 return product_(expression, (Symbol("x"), args[0], args[1]))
224 return product_(expression, *args)
225
226 def _forme_algebrique(expr):
227 "Renvoie sous forme algébrique si ce n'est pas trop long."
228 a, b = expr.as_real_imag()
229 return a + I*b
230 if algebr.count_ops() <= 1.7*expr.count_ops():
231 return algebr
232 return expr
233
234
235 def solve(expression, *variables, **kw):
236 ensemble = kw.get("ensemble", "R")
237 if not variables:
238 variables = syms(expression)
239 if len(variables) == 1:
240 # Bug de sympy si la variable est réelle.
241 # solve(sqrt(x)) renvoie une erreur par exemple.
242 # cf. test_solve_reals()
243 # On supprime toutes les assertions.
244 var = variables[0]
245 x = Dummy()
246 expression = expression.subs(var, x)
247 solutions = solve_(expression, x)
248 if ensemble == "R":
249 solutions_reelles = []
250 for solution in solutions:
251 if solution.is_real:
252 solutions_reelles.append(solution)
253 elif solution.is_real is None:
254 real, imag = solution.as_real_imag()
255 if abs(imag.evalf(n=200)) < 1e-150:
256 solutions_reelles.append(real)
257 return solutions_reelles
258 elif ensemble == "Q":
259 return [solution for solution in solutions if solution.is_rational]
260 elif ensemble == "N":
261 return [solution for solution in solutions if solution.is_integer]
262 else:
263 # On essaie de donner les solutions sous forme algébrique,
264 # si ce n'est pas trop affreux.
265 return [_forme_algebrique(s) for s in solutions]
266 else:
267 return solve_(expression, variables)
268
269 def csolve(expression, *variables):
270 return solve(expression, *variables, **{'ensemble': "C"})
271
272 def qsolve(expression, *variables):
273 return solve(expression, *variables, **{'ensemble': "Q"})
274
275 def nsolve(expression, *variables):
276 return solve(expression, *variables, **{'ensemble': "N"})
277
278 def simplifier_racines(expression):
279 try:
280 if getattr(expression, "is_Pow", False):
281 return sqrtdenest(expression)
282 elif getattr(expression, "is_Mul", False):
283 return reduce(lambda x,y:x*y, [simplifier_racines(fact) for fact in expression.args], 1)
284 elif getattr(expression, "is_Add", False):
285 return reduce(lambda x,y:x+y, [simplifier_racines(term) for term in expression.args], 0)
286 return expression
287 except Exception:
288 # sqrtdenest() renvoie assez souvent des erreurs.
289 if param.debug:
290 print("Warning: error occured during expression denesting:", expression)
291 return expression
292
293 def mat(*args):
294 """Crée une matrice.
295
296 * Si une liste est donné en argument, la liste est convertie en matrice::
297
298 >>> from wxgeometrie.mathlib.sympy_functions import mat
299 >>> mat([[1, 2], [3, 4]])
300 [1, 2]
301 [3, 4]
302 >>> mat([[1, 2, 3, 4]])
303 [1, 2, 3, 4]
304 >>> mat([1, 2, 3, 4]) # Synonyme de mat([[1], [2], [3], [4]])
305 [1]
306 [2]
307 [3]
308 [4]
309
310 * Si un entier `n` est donné en argument, une matrice identité carrée de taille `n`
311 est renvoyée::
312
313 >>> mat(3)
314 [1, 0, 0]
315 [0, 1, 0]
316 [0, 0, 1]
317
318 * Si deux entiers `n` et `p` sont donnés en arguments, une matrice zéro de taille `n*p`
319 est renvoyée::
320
321 >>> mat(1, 2)
322 [0, 0]
323
324 * On peut construire une matrice personnalisée en précisant ses dimensions
325 `n` et `p`, et l'expression générale de ses coefficients.
326 On utilise les symboles `li` et `co` pour le numéro de ligne et le numéro de colonne::
327
328 >>> from sympy import var
329 >>> var('li,co')
330 (li, co)
331 >>> mat(3, 3, li*co)
332 [0, 0, 0]
333 [0, 1, 2]
334 [0, 2, 4]
335
336 * Enfin, on peut obtenir le même résultat en donnant comme 3e argument une
337 fonction f, qui prend comme arguments le numéro de ligne et le numéro de
338 colonne::
339
340 >>> f = lambda x, y: x*y
341 >>> mat(3, 3, f)
342 [0, 0, 0]
343 [0, 1, 2]
344 [0, 2, 4]
345
346
347 * Dans l'interprete de geophar, on peut utiliser aussi les syntaxes suivantes::
348
349 mat A = 1 2 3 4 5 6 7 8 9
350 mat B = 1&2&3\\4&5&6\\7&8&9
351 """
352 assert (len(args) < 4), "La fonction mat() prend 3 arguments au maximum."
353 if len(args) == 1:
354 if isinstance(args[0], (tuple, list, Matrix)):
355 return Matrix(args[0])
356 return Matrix(Identity(args[0]))
357 elif len(args) == 2:
358 return Matrix(ZeroMatrix(*args))
359 else:
360 li = Symbol("li")
361 co = Symbol("co")
362 expr = args[2]
363 if isinstance(expr, (Fonction, FunctionType)):
364 expr = expr(li, co)
365 return Matrix(FunctionMatrix(args[0], args[1], Lambda((li, co), expr)))
366
367 def transpose(M):
368 "Transposée de la matrice M."
369 return M.T
370
371 def det(M):
372 "Déterminant de la matrice M."
373 return M.det()
374
375 def valeurs_propres(M):
376 return M.eigenvals()
377
378 def vecteurs_propres(M):
379 return M.eigenvects()
380
381 def together(expression):
382 return cancel(together_(expression))