Debian Codegraph @

wxgeometrie/mathlib/internal_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 ## Cette librairie contient des fonctions mathématiques à usage interne
25
26 from functools import reduce
27 from numpy import roots as nroots
28
29 from sympy import Mul, Float, Basic, roots, sympify, div, Symbol
30 from ..pylib import warning
31 from .. import param
32
33
34 def is_float(val):
35 return isinstance(val, (float, Float))
36
37 def is_pos(expr):
38 return getattr(expr, "is_positive", float(expr) > 0)
39
40 def is_neg(expr):
41 return getattr(expr, "is_negative", float(expr) < 0)
42
43 def is_var(expression, variable):
44 return hasattr(expression, "has") and expression.has(variable)
45
46
47 def poly_factor(polynome, variable, corps = None, approchee = None):
48 """Factorise un polynome à une variable.
49
50 Le corps peut être R ou C.
51 Par défaut, le corps de factorisation est celui des coefficients."""
52 from .sympy_functions import simplifier_racines
53 if approchee is None:
54 # Paramètre utilisé en interne par 'l'interpreteur' de commandes
55 # (cf. méth. evaluer() de la classe Interprete(), dans custom_objects.py)
56 approchee = getattr(param, 'calcul_approche', False)
57
58 if polynome.is_Mul:
59 return reduce(lambda x,y:x*y, [poly_factor(fact, variable, corps = corps) for fact in polynome.args], 1)
60 sym_poly = polynome.as_poly(variable)
61 coeffs = sym_poly.all_coeffs()
62
63 if any(is_float(coeff) for coeff in coeffs):
64 approchee = True
65 racines_brutes = {}.fromkeys(nroots(coeffs), 1)
66 else:
67 if corps == "R":
68 if not all(coeff.is_real for coeff in coeffs):
69 raise ValueError("factorisation dans 'R' impossible.")
70 elif corps is None:
71 if all(coeff.is_real for coeff in coeffs):
72 corps = "R"
73 else:
74 corps = "C"
75 racines_brutes = roots(polynome, variable, cubics=True, quartics=True)
76 racines = list((simplifier_racines(racine), mult) for racine, mult in racines_brutes.items())
77
78 if approchee:
79 nbr_racines = sum(multiplicite for racine, multiplicite in racines)
80 if nbr_racines < sym_poly.degree():
81 # On cherche une approximation des racines manquantes
82 sol_approchees = list(nroots(coeffs))
83 # On associe à chaque racine l'approximation qui lui correspond
84 for racine, multiplicite in racines:
85 distances = [(sol, abs(complex(racine) - sol)) for sol in sol_approchees]
86 distances.sort(key = lambda x:x[1])
87 for i in range(multiplicite):
88 distances.pop(0)
89 # Les racines approchées qui restent ne correspondent à aucune racine exacte
90 sol_approchees = [sol for sol, distance in distances]
91 racines.extend((sympify(sol), sol_approchees.count(sol)) for sol in set(sol_approchees))
92
93 coefficient = coeffs[0]
94 produit = 1
95 if corps == "R":
96 racines_en_stock = []
97 multiplicites_en_stock = []
98 for racine, multiplicite in racines:
99 if not isinstance(racine, Basic):
100 racine = sympify(racine)
101 reel = racine.is_real
102 if not reel:
103 # is_real n'est pas fiable (26/11/2009)
104 # cf. ((54*6**(1/3)*93**(1/2) - 162*I*6**(1/3)*31**(1/2) - 522*6**(1/3) + 6*6**(2/3)*(-522 + 54*93**(1/2))**(1/3) + 522*I*3**(1/2)*6**(1/3) + 6*I*3**(1/2)*6**(2/3)*(-522 + 54*93**(1/2))**(1/3) - 24*(-522 + 54*93**(1/2))**(2/3))/(36*(-522 + 54*93**(1/2))**(2/3))).is_real
105 re, im = racine.expand(complex=True).as_real_imag()
106 reel = im.is_zero or im.evalf(80).epsilon_eq(0,'10e-80')
107 if reel:
108 racine = re
109 # Approximation utile (?) pour la factorisation de certains polynômes de degrés 3 et 4
110 # De toute manière, une vérification de la factorisation par division euclidienne
111 # a lieu à la fin de l'algorithme.
112 if reel:
113 produit *= (variable - racine)**multiplicite
114 else:
115 conjuguee = racine.conjugate()
116 if conjuguee in racines_en_stock:
117 produit *= (variable**2 - 2*re*variable + re**2 + im**2)**multiplicite
118 i = racines_en_stock.index(conjuguee)
119 racines_en_stock.pop(i)
120 multiplicites_en_stock.pop(i)
121 else:
122 racines_en_stock.append(racine)
123 multiplicites_en_stock.append(multiplicite)
124 if racines_en_stock:
125 # Il reste des racines qu'on n'a pas réussi à appareiller.
126 P = 1
127 for racine, multiplicite in zip(racines_en_stock, multiplicites_en_stock):
128 P *= (variable - racine)**multiplicite
129 produit *= P.expand()
130 else:
131 for racine, multiplicite in racines:
132 produit *= (variable - racine)**multiplicite
133 # print produit
134 quotient, reste = div(polynome, coefficient*produit, variable)
135 if reste != 0 and not approchee:
136 ##print(polynome, coefficient*produit, variable)
137 raise NotImplementedError
138 poly_factorise = coefficient*produit*quotient
139 if isinstance(poly_factorise, Mul) and poly_factorise.args[0] == 1.:
140 poly_factorise = Mul(*poly_factorise.args[1:])
141 # sinon, poly_factor(x**2+2.5*x+1,x) donne 1.0*(x + 0.5)*(x + 2.0)
142 return poly_factorise
143
144 def syms(expression):
145 """Retourne la liste des symboles utilisés par l'expression."""
146 return tuple(expression.atoms(Symbol))
147
148 def extract_var(expression):
149 """Retourne la variable de l'expression (renvoie un avertissement s'il y en a plusieurs, et 'x' par défaut s'il n'y en a pas)."""
150 if hasattr(expression, "atoms"):
151 symboles = expression.atoms(Symbol)
152 if len(symboles) == 0:
153 return Symbol("x")
154 else:
155 if len(symboles) > 1 and param.debug:
156 warning("l'expression possede plusieurs variables.")
157 return expression.atoms(Symbol).pop()
158 else:
159 return Symbol("x")
160
161 def count_syms(expression, symbole):
162 """Compte le nombre d'occurence de la variable dans l'expression."""
163 if expression.has(symbole):
164 if expression.is_Atom:
165 return 1
166 else:
167 return sum(count_syms(arg, symbole) for arg in expression.args)
168 else:
169 return 0