Debian Codegraph @

wxgeometrie/geolib/interpolations.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------#######
4 # Interpolation #
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
25 from operator import attrgetter
26
27 from numpy import array, arange, append
28
29 try:
30 # wxgeometrie can be imported even if scipy is not found.
31 # Only Interpolation_polynomiale_par_morceaux will fail.
32 from scipy.interpolate import BPoly
33 scipy_found = True
34 except ImportError:
35 scipy_found = False
36 class BPoly:
37 def from_derivatives(*args, **kw):
38 raise NotImplementedError('Error: scipy library not found !')
39
40 from .objet import Ref, Argument, Arguments
41
42 from .courbes import Courbe_generique
43 ##from .lignes import Tangente_courbe
44 from .contexte import contexte
45
46 from ..pylib import fullrange
47 from .. import param
48
49
50
51 class Interpolation_generique(Courbe_generique):
52 """Classe mère de toutes les interpolations."""
53
54 points = __points = Arguments("Point_generique")
55
56 _style_defaut = param.interpolations
57
58 def __init__(self, *points, **styles):
59 self.__points = points = tuple(Ref(pt) for pt in points)
60 Courbe_generique.__init__(self, **styles)
61
62
63 def _affiche_extremites(self, vec_deb = None, vec_fin = None):
64 couleur = self.style("couleur")
65 niveau = self.style("niveau")
66 epaisseur = self.style("epaisseur")
67 debut = self.style("debut")
68 fin = self.style("fin")
69
70 # Début de la courbe
71 plot = self._representation[-2]
72 x, y = self.__points[0].coordonnees
73 a, b = self.__points[1].coordonnees
74 if vec_deb is None:
75 vec_deb = (a - x, b - y)
76 if debut is True:
77 plot.set_data((x,), (y,))
78 plot.set(visible=True, color=couleur, marker="o", markeredgecolor=couleur,
79 markersize=2*self.canvas.taille["o"], linewidth=epaisseur)
80 plot.zorder = niveau
81 elif debut is False:
82 arc = self.rendu.arc(x, y, vec_deb)
83 plot.set_data(*arc.get_data()) # À TESTER !!
84 plot.set(visible=True, color=couleur, linewidth=epaisseur, marker="")
85 plot.zorder = niveau
86 else:
87 plot.set_visible(False)
88
89 # Fin de la courbe
90 plot = self._representation[-1]
91 x, y = self.__points[-1].coordonnees
92 a, b = self.__points[-2].coordonnees
93 if vec_fin is None:
94 vec_fin = (a - x, b - y)
95 if fin is True:
96 plot.set_data((x,), (y,))
97 plot.set(visible=True, color=couleur, marker="o", markeredgecolor=couleur,
98 markersize=2*self.canvas.taille["o"], linewidth=epaisseur)
99 plot.zorder = niveau
100 elif fin is False:
101 arc = self.rendu.arc(x, y, vec_fin)
102 plot.set_data(*arc.get_data()) # À TESTER !!
103 plot.set(visible=True, color=couleur, linewidth=epaisseur, marker="")
104 plot.zorder = niveau
105 else:
106 plot.set_visible(False)
107
108
109
110
111 class Interpolation_lineaire(Interpolation_generique):
112 """Une interpolation linéaire.
113
114 Interpolation entre les points donnés par des segments joints (courbe de classe C0).
115 """
116
117 points = __points = Arguments("Point_generique")
118
119 def __init__(self, *points, **styles):
120 if styles.get("points", None):
121 points = styles.pop("points")
122 elif len(points) == 1 and isinstance(points[0], (list, tuple)):
123 points = points[0]
124 self.__points = points = tuple(Ref(pt) for pt in points)
125 Interpolation_generique.__init__(self, *points, **styles)
126
127 def _creer_figure(self):
128 n = len(self.__points)
129 couleur = self.style("couleur")
130 niveau = self.style("niveau")
131 style = self.style("style")
132 epaisseur = self.style("epaisseur")
133 if not self._representation:
134 self._representation = [self.rendu.ligne() for i in range(n + 1)]
135
136 self._xarray = array([])
137 self._yarray = array([])
138
139 if n < 2:
140 return
141
142 pas = self.canvas.pas()
143
144 for i in range(n - 1):
145 plot = self._representation[i]
146 x1, y1 = self.__points[i].coordonnees
147 x2, y2 = self.__points[i+1].coordonnees
148 plot.set_data(array((x1, x2)), array((y1, y2)))
149 plot.set(color=couleur, linestyle=style, linewidth=epaisseur)
150 plot.zorder = niveau
151 # TODO: améliorer l'algo de détection (notamment si l'échelle
152 # sur les 2 axes n'est pas la même).
153 # Utiliser l'algorithme des segments.
154 if abs(y2 - y1) < abs(x2 - x1):
155 x_array = arange(x1, x2, pas if x1 < x2 else -pas)
156 a = (y2 - y1)/(x2 - x1)
157 b = y1 - a*x1
158 y_array = a*x_array + b
159 elif abs(y2 - y1) > contexte['tolerance']:
160 y_array = arange(y1, y2, pas if y1 < y2 else -pas)
161 a = (x2 - x1)/(y2 - y1)
162 b = x1 - a*y1
163 x_array = a*y_array + b
164 else:
165 continue
166 self._xarray = append(self._xarray, x_array)
167 self._yarray = append(self._yarray, y_array)
168
169 self._affiche_extremites()
170
171
172 def image_par(self, transformation):
173 # FIXME: l'image n'est plus correcte si le nombre de points est modifié ensuite
174 # Par exemple, interp = Interpolation_lineaire(A, B), puis interp.points = (A, B, C)
175 return self.__class__(*(transformation(point) for point in self.__points))
176
177
178
179
180 class Interpolation_quadratique(Interpolation_generique):
181 """Une interpolation quadratique.
182
183 Interpolation des points donnés par une courbe polynomiale par morceaux, et de classe C1.
184 Pour chaque morceau, x(t)=at²+bt+c et y(t)=dt²+et+f, où t appartient à [0;1].
185 """
186 points = __points = Arguments("Point_generique")
187
188 def __init__(self, *points, **styles):
189 if "points" in styles:
190 points = styles.pop("points")
191 elif len(points) == 1 and isinstance(points[0], (list, tuple)):
192 points = points[0]
193 self.__points = points = tuple(Ref(pt) for pt in points)
194 Interpolation_generique.__init__(self, *points, **styles)
195
196
197 def _creer_figure(self):
198 n = len(self.__points)
199 couleur = self.style("couleur")
200 niveau = self.style("niveau")
201 style = self.style("style")
202 epaisseur = self.style("epaisseur")
203 if not self._representation:
204 self._representation = [self.rendu.ligne() for i in range(n + 1)]
205
206 self._xarray = array([])
207 self._yarray = array([])
208
209 if n < 2:
210 return
211
212 pas = self.canvas.pas()
213 t = fullrange(0, 1, pas)
214 for i in range(n - 1):
215 plot = self._representation[i]
216 x0, y0 = self.__points[i].coordonnees
217 x1, y1 = self.__points[i+1].coordonnees
218 if i == 0:
219 dx0, dy0 = x1 - x0, y1 - y0
220 a, b, c = x1 - dx0 - x0, dx0, x0
221 d, e, f = y1 - dy0 - y0, dy0, y0
222 u = (a*t + b)*t + c
223 v = (d*t + e)*t + f
224 plot.set_data(u, v)
225 plot.set(color=couleur, linestyle=style, linewidth=epaisseur)
226 plot.zorder = niveau
227
228 dx0 = 2*a + b
229 dy0 = 2*d + e
230
231 self._xarray = append(self._xarray, u)
232 self._yarray = append(self._yarray, v)
233
234 self._affiche_extremites(vec_fin = (dx0, dy0))
235
236
237
238
239 class Interpolation_cubique(Interpolation_generique):
240 """Une interpolation cubique.
241
242 Interpolation des points donnés par une courbe polynomiale par morceaux, de vecteur tangent horizontal aux sommets, et de classe C1 en général (ie. si x_n!=x_{n-1}).
243 Pour chaque morceau, x(t)=at^3+bt^2+ct+d et y(t)=et^3+ft^2+gt+h, où t appartient à [0;1], et y'(0)=y'(1)=0.
244 """
245
246 points = __points = Arguments("Point_generique")
247
248 def __init__(self, *points, **styles):
249 if "points" in styles:
250 points = styles.pop("points")
251 elif len(points) == 1 and isinstance(points[0], (list, tuple)):
252 points = points[0]
253 self.__points = points = tuple(Ref(pt) for pt in points)
254 Interpolation_generique.__init__(self, *points, **styles)
255
256
257 def _creer_figure(self):
258 n = len(self.__points)
259 couleur = self.style("couleur")
260 niveau = self.style("niveau")
261 style = self.style("style")
262 epaisseur = self.style("epaisseur")
263 courbure = self.style("courbure")
264 if courbure is None:
265 courbure = 1
266 if not self._representation:
267 self._representation = [self.rendu.ligne() for i in range(n + 1)]
268
269 self._xarray = array([])
270 self._yarray = array([])
271
272 if n < 2:
273 return
274
275 pas = self.canvas.pas()
276 t = fullrange(0, 1, pas)
277 for i in range(n - 1):
278 plot = self._representation[i]
279 x0, y0 = self.__points[i].coordonnees
280 x1, y1 = self.__points[i+1].coordonnees
281 if i == 0:
282 dx0 = x1 - x0
283 dy0 = y1 - y0
284 else:
285 dx0 = courbure*abs(x1 - x0)
286 if dx1 != 0:
287 dy0 = dy1/dx1*dx0
288 else:
289 dx0 = dx1
290 dy0 = dy1
291 if i < n - 2:
292 x2, y2 = self.__points[i+2].coordonnees
293 if (y0 > y1) is (y1 > y2):
294 dy1 = y2 - y0
295 dx1 = x2 - x0
296 else:
297 dy1 = 0
298 dx1 = courbure*abs(x1 - x0)
299 else:
300 dy1 = y1 - y0
301 dx1 = x1 - x0
302 a = 2*(x0 - x1) + dx0 + dx1
303 b = 3*(x1 - x0) -2*dx0 - dx1
304 c = dx0
305 d = x0
306 e = 2*(y0 - y1) + dy0 + dy1
307 f = 3*(y1 - y0) -2*dy0 - dy1
308 g = dy0
309 h = y0
310 u = ((a*t + b)*t + c)*t + d
311 v = ((e*t + f)*t + g)*t + h
312 plot.set_data(u, v)
313 plot.set(color=couleur, linestyle=style, linewidth=epaisseur)
314 plot.zorder = niveau
315
316 self._xarray = append(self._xarray, u)
317 self._yarray = append(self._yarray, v)
318
319 self._affiche_extremites(vec_deb = (dx0, dy0), vec_fin = (dx1, dy1))
320
321
322 class Interpolation_polynomiale_par_morceaux(Interpolation_generique):
323 """Une courbe d'interpolation polynomiale par morceaux.
324 Elle utilise l'interpolation par morceau de scipy pour construire la fonction,
325 via la méthode scipy.interpolate.BPoly.from_derivatives()
326
327 Elle passe par les points (xl, yl) et avec le nombre derive dans derivl à
328 l'abscisse xl.
329
330 exemple::
331
332 >>> from wxgeometrie import *
333 >>> A = Point(-1,-2)
334 >>> B = Point(2,1)
335 >>> C = Point(8,-3)
336 >>> d = Interpolation_polynomiale_par_morceaux(A,B,C, derivees=[-1,0.5,2])
337
338 :type derivee: list
339 :param derivee: value of the diff number at each point
340
341 :rtype : numpy.lib.polynomial
342
343 """
344 _style_defaut = param.interpolations_polynomiales_par_morceaux
345
346 points = __points = Arguments("Point_interpolation")
347 fonction = None # fonction d'interpolation
348
349 def __init__(self, *points, **styles):
350 debut = styles.pop("debut", True)
351 fin = styles.pop("fin", True)
352 if styles.get("points", None):
353 points = styles.pop("points")
354 # Accepter Interpolation_polynomiale_par_morceaux([A, B, C])
355 # comme alias de Interpolation_polynomiale_par_morceaux(A, B, C).
356 elif len(points) == 1 and isinstance(points[0], (list, tuple)):
357 points = points[0]
358 self.__points = points = tuple(Ref(pt) for pt in points)
359 # en test: creation des tangentes: dictionnaire
360 # key: nom du point, value: objet Tangente_courbe
361 ##self.__tangentes = []
362 # boucle avec ruse enumerate
363 # cf http://docs.python.org/tutorial/datastructures.html#dictionaries
364 ##for i, P in enumerate(points):
365 ##dico = {'point': P, 'cdir': self.__derivees[i]}
366 ##self.__tangentes.append(Tangente_courbe(**dico))
367
368 Interpolation_generique.__init__(self, *points, **styles)
369
370
371 @property
372 def fonction(self):
373 """Fonction wrapper vers la fonction de scipy BPoly.from_derivatives
374
375 """
376 pts = self.points_tries
377 xl = [P.x for P in pts]
378 yl = [P.y for P in pts]
379 yl_cum = list(zip(yl, self._derivees()))
380 return BPoly.from_derivatives(xl, yl_cum)
381
382
383 def _derivees(self):
384 derivees = []
385 points = self.points_tries
386 n = len(points)
387 for i, P in enumerate(points):
388 if P.derivee is None:
389 if n == 1:
390 derivees.append(0)
391 elif i == 0:
392 # Premier point de la courbe
393 A, B = points[:2]
394 dy = B.y - A.y
395 dx = B.x - A.x
396 derivees.append(dy/dx if dx else 0)
397 elif i == n - 1:
398 # Dernier point de la courbe
399 A, B = points[-2:]
400 dy = B.y - A.y
401 dx = B.x - A.x
402 derivees.append(dy/dx if dx else 0)
403 else:
404 # Il y a (au moins) un point avant et un point après
405 A, B, C = points[i - 1:i + 2]
406 if B.y >= max(A.y, C.y) or B.y <= min(A.y, C.y):
407 derivees.append(0)
408 else:
409 der = self.strategies.get(self.style('strategie'),
410 self._strategie_pente_moyenne)
411 derivees.append(der(self, A, B, C))
412 else:
413 derivees.append(P.derivee)
414 return derivees
415
416
417 def _strategie_pente_moyenne(self, A, B, C):
418 """La pente en B est celle de la droite (AC).
419
420 Stratégie simple et qui donne un rendu assez esthétique en pratique.
421 """
422 dy = C.y - A.y
423 dx = C.x - A.x
424 return dy/dx if dx else 0
425
426 def _strategie_pente_minimale(self, A, B, C):
427 """Pente la plus faible entre celle de (AB) et celle de (BC).
428
429 On prend la pente la plus faible, de façon à être sûr
430 qu'à gauche et à droite du point considéré, la courbe d'interpolation
431 reste comprise en ordonnées entre le point considéré et
432 le point suivant.
433 Cela facilite la construction d'extrema :
434 si A, B, C sont trois points d'interpolation,
435 avec B.y < A.y et B.y < C.y, alors on est assuré que
436 la courbe ne descendra pas en dessous de B.y sur
437 l'intervalle [A.x, C.x].
438 """
439 dy1 = B.y - A.y
440 dx1 = B.x - A.x
441 der1 = (dy1/dx1 if dx1 else 0)
442 dy2 = C.y - B.y
443 dx2 = C.x - B.x
444 der2 = (dy2/dx2 if dx2 else 0)
445 return der1 if abs(der1) < abs(der2) else der2
446
447 def _strategie_moyenne_gauche_droite(self, A, B, C):
448 """
449 Moyenne de la pente moyenne à gauche et de la pente moyenne à droite.
450
451 Stratégie peu concluante en pratique.
452 Il faudrait utiliser un barycentre plutôt qu'une moyenne simple.
453 """
454 dy1 = B.y - A.y
455 dx1 = B.x - A.x
456 der1 = (dy1/dx1 if dx1 else 0)
457 dy2 = C.y - B.y
458 dx2 = C.x - B.x
459 der2 = (dy2/dx2 if dx2 else 0)
460 return .5*(der1 + der2)
461
462
463 strategies = {'pente_moyenne': _strategie_pente_moyenne,
464 'pente_minimale': _strategie_pente_minimale,
465 'moyenne_gauche_droite': _strategie_moyenne_gauche_droite
466 }
467
468
469 @property
470 def points_tries(self):
471 # TODO: mise en cache
472 return sorted(self.__points, key=attrgetter('x'))
473
474
475 def _creer_figure(self):
476 points = self.points_tries
477 n = len(points)
478 couleur = self.style("couleur")
479 niveau = self.style("niveau")
480 style = self.style("style")
481 epaisseur = self.style("epaisseur")
482 if not self._representation:
483 self._representation = [self.rendu.ligne() for i in range(3)]
484
485 if n < 2:
486 return
487 # de même les tangentes sont recalculées
488 # il doit y avoir moyen de faire moins de calculs
489 # self.__tangentes = []
490 # for i in range(len(self.__points)):
491 # self.__tangentes.append(Tangente_courbe(point = self.__points[i],\
492 # cdir = self.__derivees[i]))
493 # #self.__tangentes[i]._creer_figure()
494
495 pas = self.canvas.pas()
496 plot = self._representation[0]
497 x1, y1 = points[0].coordonnees
498 x2, y2 = points[-1].coordonnees
499 xarray = fullrange(x1, x2, pas)
500 yarray = self.fonction(xarray)
501 plot.set_data(xarray, yarray)
502 plot.set(color=couleur, linestyle=style, linewidth=epaisseur)
503 plot.zorder = niveau
504 self._xarray = xarray
505 self._yarray = yarray
506
507 self._affiche_extremites()
508
509 @property
510 def xmin(self):
511 return self.points_tries[0].x if self.__points else None
512
513 @property
514 def xmax(self):
515 return self.points_tries[-1].x if self.__points else None
516