Debian Codegraph @

wxgeometrie/geolib/routines.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------#######
4 # Geolib #
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 math import cos, sin, hypot, ceil, floor, sqrt, pi, log10, copysign
27 import re
28 from functools import partial
29
30 import numpy
31
32 from sympy import sqrt as s_sqrt
33 from .contexte import contexte
34 from ..mathlib.universal_functions import arg as u_arg, sqrt as u_sqrt
35 from ..mathlib.printers import custom_str
36
37
38
39 def confondus(M, N):
40 try:
41 (xM, yM), (xN, yN) = M, N
42 except Exception:
43 return False
44 eps = contexte['tolerance']
45 return abs(xN - xM) < eps and abs(yM - yN) < eps
46
47
48 def distincts(M, N):
49 try:
50 (xM, yM), (xN, yN) = M, N
51 except Exception:
52 return False
53 eps = contexte['tolerance']
54 return abs(xN - xM) > eps or abs(yM - yN) > eps
55
56
57 def distincts2a2(*points):
58 for i, M in enumerate(points):
59 for N in points[i + 1:]:
60 if not distincts(M, N):
61 return False
62 return True
63
64
65 def radian(val):
66 unite = contexte['unite_angle']
67 if unite == 'd':
68 return 180*val/pi
69 elif unite == 'g':
70 return 200*val/pi
71 assert unite == 'r'
72 return val
73
74
75 ## Fonctions rapides destinées essentiellement à géolib
76
77 def produit_scalaire(u, v):
78 """Calcule le produit scalaire des vecteurs u et v.
79 u et v doivent être de type list, tuple, array, ou geolib.Vecteur."""
80 return sum(i*j for i, j in zip(u ,v))
81
82
83
84 #def angle_vectoriel(u, v):
85 # u"""Renvoie une mesure sur ]-pi;pi] de l'angle formé par les vecteurs u et v.
86 # u et v doivent être de type list, tuple, array, ou geolib.Vecteur, et de dimension 2."""
87 # return clog(complex(*v)/complex(*u)).imag
88
89 def angle_vectoriel(u, v):
90 """Renvoie une mesure sur ]-pi;pi] de l'angle formé par les vecteurs u et v.
91 u et v doivent être de type list, tuple, array, ou geolib.Vecteur, et de dimension 2.
92
93 Version compatible avec sympy."""
94 return u_arg((v[0] + v[1]*1j)/(u[0] + u[1]*1j))
95
96 #~ def _angle_vectoriel_bis_(u, v):
97 #~ u"Autre implémentation du produit vectoriel (un peu plus lente)."
98 #~ return (cmp(u[0]*v[1]-v[0]*u[1], 0) or 1)*acos(produit_scalaire(u, v)/(hypot(*u)*hypot(*v)))
99
100
101 def norme(x, y):
102 "Implémentation rapide de la norme d'un vecteur."
103 if isinstance(x, (int, float)) or isinstance(y, (int, float)):
104 return hypot(x, y)
105 return u_sqrt(x**2 + y**2)
106
107
108
109 def distance(A, B):
110 "Distance entre les points A et B."
111 xA, yA = A
112 xB, yB = B
113 return norme(xA - xB, yA - yB)
114
115 def carre_distance(A, B):
116 "Carré de la distance entre les points A et B."
117 xA, yA = A
118 xB, yB = B
119 return (xB - xA)**2+(yB - yA)**2
120
121 def vect(A, B):
122 "Coordonnées du vecteur A>B."
123 xA, yA = A
124 xB, yB = B
125 return xB - xA, yB - yA
126
127 def det(vec1, vec2):
128 "Déterminant de deux vecteurs du plan."
129 x1, y1 = vec1
130 x2, y2 = vec2
131 return x1*y2 - x2*y1
132
133 ## Fonctions de formatage (pour l'affichage entre autres)
134
135 #~ def old_nchiffres(x, n = 1):
136 #~ u"Arrondi x en fournissant n chiffres significatifs. Ex: nchiffres(2345, 2)."
137
138 #~ return x and round(x/10**floor(log10(abs(x))-n+1))*10**floor(log10(abs(x))-n+1) # Attention au cas x = 0 !
139
140
141 def array_zip(*args):
142 return (numpy.array(item) for item in zip(*args))
143
144
145 # Les deux fonctions qui suivent sont bien plus rapides que la classe Polynome pour fournir des solutions approchees.
146 # Elles servent comme routine dans geolib par exemple.
147
148 def delta(a, b, c):
149 return b**2 - 4*a*c
150
151 def racines(a, b, c, exact=False):
152 d = delta(a, b, c)
153 if not d:
154 return [-b/(2*a)]
155 if d > 0:
156 rac = (s_sqrt(d) if exact else sqrt(d))
157 return [(-rac-b)/(2*a) , (rac-b)/(2*a)]
158 return []
159
160
161
162
163 def point_dans_polygone(couple, polygone):
164 """Détermine si un point est à l'intérieur d'un polygone.
165 D'après un algorithme de Paul Bourke."""
166 x, y = couple
167 dedans = False
168 n = len(polygone)
169 p1x, p1y = polygone[0]
170 for i in range(1, n + 1):
171 p2x, p2y = polygone[i % n]
172 if min(p1y, p2y) < y <= max(p1y, p2y) and x <= max(p1x, p2x):
173 if p1y != p2y:
174 xinters = (y - p1y)*(p2x - p1x)/(p2y - p1y) + p1x
175 if p1x == p2x or x <= xinters:
176 dedans = not dedans
177 p1x, p1y = p2x, p2y
178
179 return dedans
180
181
182 def enveloppe_convexe(*points):
183 """Donne l'enveloppe convexe d'un ensemble de points.
184 D'après Dinu C. Gherman (Andrew's Monotone Chain Algorithm)."""
185 def det(p, q, r):
186 return (q[0]*r[1] + p[0]*q[1] + r[0]*p[1]) - (q[0]*p[1] + r[0]*q[1] + p[0]*r[1])
187
188 # Get a local list copy of the points and sort them.
189 points = sorted(points)
190 # Build upper half of the hull.
191 upper = [points[0], points[1]]
192 for p in points[2:]:
193 upper.append(p)
194 # Le déterminant est positif ssi l'on tourne à gauche
195 while len(upper) > 2 and det(*upper[-3:]) >= 0:
196 del upper[-2]
197 # Build lower half of the hull.
198 points.reverse()
199 lower = [points[0], points[1]]
200 for p in points[2:]:
201 lower.append(p)
202 while len(lower) > 2 and det(*lower[-3:]) >= 0:
203 del lower[-2]
204 # Remove duplicates.
205 del lower[0], lower[-1]
206 # Concatenate both halfs and return.
207 return upper + lower
208
209
210 def point_dans_enveloppe_convexe(point, polygone):
211 """Détermine si un point est à l'intérieur de l'enveloppe convexe d'un polygone."""
212 def det(p, q, r):
213 return (q[0]*r[1] + p[0]*q[1] + r[0]*p[1]) - (q[0]*p[1] + r[0]*q[1] + p[0]*r[1])
214
215 xmin = min(pt[0] for pt in polygone)
216 xmax = max(pt[0] for pt in polygone)
217 ymin = min(pt[1] for pt in polygone)
218 ymax = max(pt[1] for pt in polygone)
219 if not(xmin < point[0] < xmax and ymin < point[1] < ymax):
220 return False
221 # Get a local list copy of the points and sort them.
222 points = sorted(tuple(polygone) + (point,))
223 # Build upper half of the hull.
224 upper = [points[0], points[1]]
225 for p in points[2:]:
226 upper.append(p)
227 # Le déterminant est positif ssi l'on tourne à gauche
228 while len(upper) > 2 and det(*upper[-3:]) >= 0:
229 del upper[-2]
230 if point in upper:
231 return False
232 # Build lower half of the hull.
233 points.reverse()
234 lower = [points[0], points[1]]
235 for p in points[2:]:
236 lower.append(p)
237 while len(lower) > 2 and det(*lower[-3:]) >= 0:
238 del lower[-2]
239 return point not in lower
240
241 '''
242 def distance_point_ellipse(centre, rx, ry, point):
243 u"""Distance approchée entre un point et une ellipse orientée selon les axes.
244
245 D'après http://www.spaceroots.org/documents/distance/node9.html"""
246 a, b = centre
247 x, y = point
248 # L'ellipse est déjà orientée selon les axes, on prend le centre de l'ellipse comme origine
249 x -= a
250 y -= b
251 # On se ramène au premier cadran, (Ox) et (Oy) étant des axes de symétrie de l'ellipse
252 x = abs(x)
253 y = abs(y)
254 # On s'arrange pour que rx soit le semi-grand axe
255 if rx < ry:
256 rx, ry = ry, rx
257 x, y = y, x
258 # Cas particulier : ellipse réduite à un point
259 if rx < param.tolerance:
260 return x**2 + y**2
261 f = (rx - ry)/rx
262 # Cas particulier : le point est confondu avec le centre de l'ellipse
263 if x**2 + y**2 < param.tolerance**2:
264 return ry
265 # Cas général : http://www.spaceroots.org/documents/distance/node9.html
266 s = sqrt(x**2 + y**2)
267 cos0 = x/s
268 sin0 = y/s
269 t0 = sin0/(1 - cos0)
270 a = ((1 - f)*cos0)**2 + sin0**2
271 b = (1 - f)**2*x*cos0 + y*sin0
272 c = (1 - f)**2*(x**2 - rx**2) + y**2
273 k0 = c/(b + sqrt(b**2 - a*c))
274 # Nouveau point :
275 x0 = x - k*cos0
276 y0 = x - k*sin0
277 phi = atan2(y, x*(1 - f)**2)
278 '''
279
280
281 def carre_distance_point_ellipse(centre, rx, ry, point, epsilon = None):
282 """Distance approchée entre un point et une ellipse orientée selon les axes.
283
284 Algorithme naïf, d'après moi-même. ;-)"""
285 if epsilon is None:
286 epsilon = contexte["tolerance"]
287 xO, yO = centre
288 x, y = point
289 # L'ellipse est déjà orientée selon les axes, on prend le centre de l'ellipse comme origine
290 x -= xO
291 y -= yO
292 # On se ramène au premier cadran, (Ox) et (Oy) étant des axes de symétrie de l'ellipse
293 x = abs(x)
294 y = abs(y)
295 rx = abs(rx)
296 ry = abs(ry)
297 def f(t):
298 return (rx*cos(t) - x)**2 + (ry*sin(t) - y)**2
299 a = 0
300 b = pi/2
301 while b - a > epsilon:
302 i = (a + b)/2
303 fim = f(i - epsilon)
304 fi = f(i)
305 fip = f(i + epsilon)
306 if fim < fi < fip:
307 b = i
308 elif fim > fi > fip:
309 a = i
310 else:
311 break
312 return fi
313
314
315
316 def segments_secants(p1, p2, p3, p4):
317 d1 = direction_droite(p3, p4, p1)
318 d2 = direction_droite(p3, p4, p2)
319 d3 = direction_droite(p1, p2, p3)
320 d4 = direction_droite(p1, p2, p4)
321 return ((d1>0 and d2<0) or (d1<0 and d2>0)) and ((d3>0 and d4<0) or (d3<0 and d4>0))
322
323 def direction_droite(pi, pj, pk):
324 xi, yi = pi
325 xj, yj = pj
326 xk, yk = pk
327 return (xk - xi)*(yj - yi) - (yk - yi)*(xj - xi)
328
329
330
331 def trigshift(t, a = 0):
332 "Retourne le représentant de t[2pi] situé dans l'intervalle [a; a+2pi[."
333 return t + 2*pi*ceil((a - t)/(2*pi))
334
335
336 def distance_segment(M, A, B, d):
337 """Teste si la distance entre le point M et le segment [AB] est inférieure à d.
338
339 M, A et B sont des couples de réels, et d un réel.
340 Cf. "distance_point_segment.odt" dans "developpeurs/maths/".
341 """
342 x, y = M
343 if A is None or B is None:
344 if A is None and B is None:
345 return False
346 A = B = A or B
347 xA, yA = A
348 xB, yB = B
349 x1 = min(xA, xB) - d; x2 = max(xA, xB) + d
350 y1 = min(yA, yB) - d; y2 = max(yA, yB) + d
351 if x1 < x < x2 and y1 < y < y2:
352 norme2 = ((xB - xA)**2 + (yB - yA)**2)
353 if norme2 > contexte['tolerance']:
354 return ((yA - yB)*(x - xA) + (xB - xA)*(y - yA))**2/norme2 < d**2
355 else: # les extrémités du segment sont confondues
356 return (x - xA)**2 + (y - yA)**2 < d**2
357 else:
358 return False
359
360
361 # ----------------------
362 # Fonctions de formatage
363 # ----------------------
364
365 def nchiffres(x, n = 1):
366 """Arrondi x en fournissant n chiffres significatifs.
367
368 >>> from wxgeometrie.geolib.routines import nchiffres
369 >>> nchiffres(2345, 2)
370 2300.0
371 """
372 if x:
373 k = 10**floor(log10(abs(x))-n+1)
374 return round(x/k)*k
375 return x # Attention au cas x = 0 !
376
377
378 TRAILING_ZEROS = re.compile(r"\.[0-9]*0+(?![0-9])")
379
380 def strip_trailing_zeros(s):
381 """"Supprime tous les zeros inutiles des nombres flottants.
382
383 >>> from wxgeometrie.geolib.routines import strip_trailing_zeros
384 >>> strip_trailing_zeros("4.0000")
385 '4'
386 >>> strip_trailing_zeros("4.200*x + 3.007*y + 5.0*z + .010 = 0")
387 '4.2*x + 3.007*y + 5*z + .01 = 0'
388 """
389 return re.sub(TRAILING_ZEROS, lambda m:m.group().rstrip('0').rstrip('.'), s)
390
391
392 def nice_display(x):
393 if isinstance(x, float):
394 x = round(x, contexte["decimales"])
395 if abs(x - int(x)) < contexte["tolerance"]:
396 x = int(x)
397 elif hasattr(x, 'valeur'):
398 return nice_display(x.valeur)
399 s = strip_trailing_zeros(str(x).replace('**', '^'))
400 if contexte["separateur_decimal"] == ',':
401 s = s.replace('.', ',')
402 return s
403
404
405 def arrondir(x):
406 """Arrondi le nombre : un seul chiffre significatif, compris entre 1 et 5.
407 Transforme automatiquement le nombre en entier selon le cas."""
408 n = nchiffres(x, sqrt(.5))
409 if int(n) == n:
410 n = int(n)
411 return n
412
413
414 def arrondir_1_2_5(x):
415 """Arrondit x à un nombre de la forme k*10^p, avec k dans {1, 2, 5},
416 et p entier relatif.
417
418 >>> from wxgeometrie.geolib.routines import arrondir_1_2_5
419 >>> arrondir_1_2_5(250)
420 200.0
421 >>> arrondir_1_2_5(4527)
422 5000.0
423 >>> arrondir_1_2_5(0.0078)
424 0.01
425 """
426 p = floor(log10(abs(x)))
427 k = x/10**p
428 if k < 1.4142135623730951:
429 # 10**(log10(2)/2)
430 k = 1
431 elif k < 3.1622776601683795:
432 # 10**((log10(2)+log10(5))/2)
433 k = 2
434 elif k < 7.0710678118654746:
435 # 10**((log10(5) + 1)/2)
436 k = 5
437 else:
438 k = 1
439 p += 1
440 return k*10**p
441
442
443 def arrondir_1_25_5(x):
444 """Arrondit x à un nombre de la forme k*10^p, avec k dans {1, 2.5, 5},
445 et p entier relatif.
446
447 >>> from wxgeometrie.geolib.routines import arrondir_1_25_5
448 >>> arrondir_1_25_5(200)
449 250.0
450 >>> arrondir_1_25_5(4527)
451 5000.0
452 >>> arrondir_1_25_5(0.0078)
453 0.01
454 """
455 p = floor(log10(abs(x)))
456 k = x/10**p
457 if k < 1.5811388300841898:
458 # 10**(log10(2.5)/2)
459 k = 1
460 elif k < 3.5355339059327378:
461 # 10**((log10(2.5)+log10(5))/2)
462 k = 2.5
463 elif k < 7.0710678118654746:
464 # 10**((log10(5) + 1)/2)
465 k = 5
466 else:
467 k = 1
468 p += 1
469 return k*10**p
470
471
472
473 def formatage(eqn):
474 """Améliore l'affichage des équations.
475
476 >>> from wxgeometrie.geolib.routines import formatage
477 >>> formatage('1 x + -1/3 y + 1 = 0')
478 'x - 1/3 y + 1 = 0'
479 >>> formatage('-1 x + -1 y + -1 = 0')
480 '-x - y - 1 = 0'
481 >>> formatage('2 x + 0 y - 28 = 0')
482 '2 x - 28 = 0'
483 >>> formatage(u'x\xb2 + y\xb2 + -1 x + -4/3 y + -47/36 = 0') == u'x\xb2 + y\xb2 - x - 4/3 y - 47/36 = 0'
484 True
485 """
486 #FIXME: pour l'instant, ça ne marche qu'avec x et y (il ne faut
487 # pas qu'il y ait de xy dans l'équation, ni de t, etc.)
488 if eqn.startswith('1 '):
489 eqn = eqn[2:]
490 return eqn.replace("+ -1", "- 1").replace('-1 x', '-x').replace('-1 y', '-y')\
491 .replace("+ -", "- ").replace('- 1 x', '- x').replace('- 1 y', '- y')\
492 .replace('+ 1 x', '+ x').replace('+ 1 y', '+ y')\
493 .replace('+ 0 x ', '').replace('+ 0 y ', '').replace('+ 0 ', '')
494
495
496 def nice_str(x):
497 """Convertit en chaîne de caractères les objets mathématiques.
498
499 Améliore le formatage de ces objets:
500 * Supprime les 0 inutiles.
501
502 >>> from wxgeometrie.geolib.routines import nice_str
503 >>> nice_str(8.0)
504 '8'
505
506 * Remplace le point par une virgule pour les décimaux.
507
508 >>> nice_str(8.2)
509 '8,2'
510
511 * Personnalise un peu l'affichage de certains objets sympy,
512 pour correspndre aux notations française.
513
514 >>> from sympy import oo, log
515 >>> nice_str(oo)
516 '+oo'
517 >>> nice_str(log(7))
518 'ln(7)'
519
520 """
521 return strip_trailing_zeros(custom_str(x)).replace('.', ',')
522
523
524 sign = partial(copysign, 1)