Debian Codegraph @

wxgeometrie/mathlib/custom_objects.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 ## Objets complémentaires à ceux de sympy
25
26 import threading
27
28 from sympy import Symbol, Rational, Expr, Integer, Basic, evaluate
29 from sympy.core.cache import cacheit
30 from sympy.core.numbers import Infinity
31
32 from .internal_objects import ObjetMathematique
33 from ..pylib import GenericWrapper
34
35
36
37 def convert2decim(expr, prec=None):
38 if not isinstance(expr, Basic):
39 return expr
40 dico = {}
41 for a in expr.atoms():
42 if a.is_Rational:
43 dico[a] = Decim(a, prec=prec)
44 with evaluate(False):
45 return expr.subs(dico)
46
47
48
49
50 class Decim(Rational):
51 """
52 Fonctionne comme un rationnel sympy, mais s'affiche comme un décimal.
53
54 Ceci permet, dans la calculatrice, de faire des calculs avec des décimaux,
55 tout en ayant en interne des résultats exacts, et donc d'éviter les cumuls
56 d'erreurs d'arrondis.
57 """
58
59 __slots__ = ['p', 'q', 'prec']
60
61 _op_priority = 10000
62
63 @cacheit
64 def __new__(cls, p, q=None, prec=15):
65 rat = Rational.__new__(cls, p, q)
66 if isinstance(rat, (Integer, Infinity)):
67 return rat
68 obj = Expr.__new__(cls)
69 obj.p = rat.p
70 obj.q = rat.q
71 obj.prec = prec
72 return obj
73
74 def to_Rational(self):
75 return Rational(self.p, self.q)
76
77 def __neg__(self):
78 return Decim(-self.p, self.q, prec=self.prec)
79
80 def __abs__(self):
81 return Decim(abs(self.p), self.q, prec=self.prec)
82
83 # On modifie les méthodes __add__, __sub__, etc. de Rational()
84 # pour renvoyer un objet Decim() si l'un des objets de l'opération
85 # est de type Decim.
86
87 # La difficulté est que sympy à chaque calcul effectue des simplifications
88 # ou des calculs intermédiaires qui remplacent les objets `Decim` par
89 # des objets `Rational`.
90 # Il faut donc convertir à la fin de l'opération les objets `Rational`
91 # en objets `Decim` (qui sont en fait des rationnels s'affichant sous
92 # forme décimale).
93 # On hacke donc les méthodes opératoires (__add__, __mul__, ...)
94 # de `Rational`, pour effectuer cette conversion à la fin.
95 # Comme les opérations provoquent souvent un grand nombre d'appels
96 # récursifs en interne dans `sympy`, on implémente un gestionnaire de
97 # contexte qui permet de savoir si on est dans le calcul principal
98 # où dans un sous-calcul (appel récursif).
99 # On effectue la conversion `Rational` -> `Decim` uniquement à la fin
100 # du calcul principal, et non dans les appels récursifs.
101 # Ceci permet d'optimiser le temps de calcul.
102
103
104 class CallContext:
105 calls = {} # {thread_id: integer}
106 prec = {} # {thread_id: integer}
107 def __enter__(self):
108 id = threading.get_ident()
109 if id not in self.calls:
110 self.calls[id] = 0
111 self.prec[id] = float('-inf')
112 self.calls[id] += 1
113 return self
114
115 def __exit__(self, type, value, traceback):
116 id = threading.get_ident()
117 self.calls[id] -= 1
118 if self.calls[id] == 0:
119 self.prec[id] = float('-inf')
120
121 def add_prec(self, val):
122 id = threading.get_ident()
123 self.prec[id] = max(val, self.prec[id])
124
125 def get_prec(self):
126 id = threading.get_ident()
127 return (self.prec[id] if self.prec[id] > float('-inf') else None)
128
129 def is_first_call(self):
130 id = threading.get_ident()
131 return self.calls[id] == 1
132
133
134
135 def _compatible(meth):
136 "Modifie la méthode `meth` pour qu'elle prenne en compte le type Decim()."
137 def new_meth(self, other, *args):
138 with CallContext() as call_context:
139 result = meth(self, other, *args)
140 precs = []
141 if isinstance(self, Decim):
142 call_context.add_prec(self.prec)
143 # ~ assert call_context.get_prec() is not None
144 if isinstance(other, Decim):
145 call_context.add_prec(other.prec)
146 # ~ assert call_context.get_prec() is not None
147
148 prec = call_context.get_prec()
149 if prec is not None and call_context.is_first_call():
150 if isinstance(result, Rational):
151 result = Decim(result, prec=prec)
152 else:
153 result = convert2decim(result, prec=prec)
154 return result
155 return new_meth
156
157 for _name in ('__add__', '__radd__', '__sub__', '__mul__',
158 #'__div__', '__rdiv__', ### in sympy-1.7.1 tose attributes do not exist in Rational, neither in Integer
159 #'__pow__', ### in sympy's new version, there are 3 arguments.
160 '__rpow__', '__mod__', '__rmod__',
161 '_eval_power', '__truediv__'):
162 setattr(Rational, _name, _compatible(getattr(Rational, _name)))
163 setattr(Integer, _name, _compatible(getattr(Integer, _name)))
164
165 del _name, _compatible
166
167
168 class Fonction(ObjetMathematique):
169 """Une fonction de une ou plusieurs variables."""
170 def __init__(self, variables, expression):
171 if not isinstance(variables, (list, tuple)):
172 variables = (variables,)
173 self.variables = variables
174 self.expression = expression
175
176 @classmethod
177 def _substituer(cls, expression, dico):
178 if hasattr(expression, "__iter__"):
179 return expression.__class__(cls._substituer(elt, dico) for elt in expression)
180 return expression.subs(dico)
181
182 def __call__(self, *args, **kw):
183 if kw:
184 if args:
185 raise TypeError("les arguments sont entres de deux facons differentes.")
186 return self._substituer(self.expression, [(Symbol(key), value) for key, value in kw.items()])
187 if len(args) > len(self.variables):
188 raise TypeError("il y a plus d'arguments que de variables.")
189 return self._substituer(self.expression, list(zip(self.variables[:len(args)], args)))
190
191 def _variables(self):
192 return tuple(str(arg) for arg in self.variables)
193
194 def __str__(self):
195 return ", ".join(self._variables()) + " -> " + str(self.expression)
196
197 def __repr__(self):
198 return "Fonction(%s, %s)" %(repr(self.variables), repr(self.expression))
199
200 for op in ("add", "mul", "div", "rdiv", "pow", "rpow"):
201 op = "__" + op + "__"
202 def __op__(self, y, op = op):
203 if isinstance(y, Fonction):
204 if self.variables == y.variables or not y.variables:
205 return Fonction(self.variables, getattr(self.expression, op)(y.expression),)
206 elif not self.variables:
207 return Fonction(y.variables, getattr(self.expression, op)(y.expression),)
208 else:
209 raise ValueError("les deux fonctions n'ont pas les memes variables.")
210 else:
211 return Fonction(self.variables, getattr(self.expression, op)(y),)
212 exec("%s=__op__" %op)
213 del __op__, op
214
215 def __ne__(self):
216 return Fonction(self.variables, -self.expression)
217
218 def __abs__(self):
219 return Fonction(self.variables, abs(self.expression))
220
221 def __eq__(self, y):
222 if isinstance(y, Fonction):
223 return self.expression == y.expression
224 else:
225 return self.expression == y
226
227 def __gt__(self, y):
228 if isinstance(y, Fonction):
229 return self.expression > y.expression
230 else:
231 return self.expression > y
232
233
234 class ProduitEntiers(int):
235 """Usage interne : destiné à être utilisé avec sympy.factorint."""
236
237 def __new__(cls, *couples):
238 val = 1
239 for (m, p) in couples:
240 val *= m**p
241 self = int.__new__(cls, val)
242 self.couples = couples
243 return self
244
245 # __slots__ = ["couples"]
246
247 def __str__(self):
248 def formater(exposant):
249 if exposant == 1:
250 return ""
251 return "**" + str(exposant)
252 return "*".join((str(entier) + formater(exposant)) for entier, exposant in self.couples)
253
254 def __repr__(self):
255 return "ProduitEntiers(*%s)" %repr(self.couples)
256
257
258
259
260 #TODO: créer une classe Wrapper, dont MesureDegres doit hériter,
261 # Note: this must wrap all special methods
262 # http://docs.python.org/reference/datamodel.html#more-attribute-access-for-new-style-classes
263 class MesureDegres(GenericWrapper):
264 """Usage interne : destiné à être utilisé avec deg."""
265
266 __slots__ = ('__val',)
267
268 def __str__(self):
269 return str(self.__val) + '°'
270
271 def __repr__(self):
272 return repr(self.__val) + '°'
273
274
275
276
277
278 class Temps(object):
279 def __init__(self, secondes = 0, **kw):
280 self.secondes = secondes + kw.get("s", 0) \
281 + 60*kw.get("m", 0) + 60*kw.get("min", 0) \
282 + 3600*kw.get("h", 0) \
283 + 86400*kw.get("j", 0) + 86400*kw.get("d", 0)
284
285 def jhms(self):
286 s = float(self.secondes)
287 s, dec = int(s), s-int(s)
288 j, s = s//86400, s%86400
289 h, s = s//3600, s%3600
290 m, s = s//60, s%60
291 if dec:
292 s += dec
293 return j, h, m, s
294
295 def __str__(self):
296 return "%s j %s h %s min %s s" % self.jhms()
297
298 def __repr__(self):
299 return "Temps(%s)" %self.secondes
300