Debian Codegraph @

wxgeometrie/geolib/backends/backend_tikz.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##---------------------------------------#######
4 # Backends #
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 from math import pi
25 from re import sub, compile
26
27 from ...mathlib.intervalles import conversion_chaine_ensemble
28 from ...mathlib.parsers import traduire_formule, NBR_SIGNE_OR_VAR
29
30
31 # \usetikzlibrary{arrows.meta}
32
33 class BackendTikz(object):
34
35 _arrow = '-{Stealth[scale=1.7]}'
36
37 _dict_styles_traits = {':': 'dotted', '--': 'dashed', '-': 'solid',
38 '.-': 'dashdotted', '-.': 'dashdotted'}
39
40 _dict_couleurs = {'g': 'green', 'r': 'red', 'b': 'blue', 'y': 'yellow',
41 'k': 'black', 'c': 'cyan', 'm': 'magenta', 'w': 'white'}
42
43 def _style_trait(self, style):
44 return self._dict_styles_traits.get(style, '')
45
46 def _epaisseur(self, value):
47 'Convertit la largeur de ligne.'
48 return str(value/2) + 'pt'
49
50 def _couleur(self, couleur):
51 if isinstance(couleur, tuple):
52 r, g, b, a = couleur
53 return '{rgb:red,%s;green,%s;blue,%s}' % (r, g, b)
54 else:
55 return self._dict_couleurs.get(couleur, couleur)
56
57 def _add(self, commande):
58 self._lignes.append(commande)
59
60 def _draw(self, path, options=[], arrow=False, node='', **style):
61 options = options[:] # Attention à bien recréer une nouvelle liste !
62 if isinstance(path, (list, tuple)):
63 path = ' -- '.join('(%s, %s)' % (x, y) for x, y in path)
64 if 'couleur' in style:
65 options.append('color=' + self._couleur(style['couleur']))
66 if 'style' in style:
67 options.append(self._style_trait(style['style']))
68 if 'epaisseur' in style:
69 options.append('line width=' + self._epaisseur(style['epaisseur']))
70 if arrow:
71 options.append(self._arrow)
72 if node:
73 node = ' node ' + node
74 self._add(r'\draw[%s] %s%s;' % (', '.join([_f for _f in options if _f]), path, node))
75
76 def exporter(self, feuille, **options):
77 deb = r'\begin{tikzpicture}'
78 tikz_options = options.get('tikz', {})
79 tikz_options['scale'] = options['echelle']
80 deb += '[%s]' % ','.join('%s=%s' %(key, val) for (key, val) in tikz_options.items())
81 self._lignes = [deb]
82 self._export_repere(feuille)
83 for objet in feuille.liste_objets(objets_caches=False, etiquettes=False):
84 for classe in objet.__class__.__mro__:
85 methode = '_export_' + classe.__name__
86 if hasattr(self, methode):
87 getattr(self, methode)(objet, **options)
88 break
89 self._lignes.append(r'\end{tikzpicture}')
90 return '\n'.join(self._lignes)
91
92 def _export_repere(self, feuille, **options):
93 xmin, xmax, ymin, ymax = feuille.fenetre_reellement_affichee()
94 xgradu, ygradu = feuille.gradu
95 origine, abscisse, ordonnee = feuille.repere
96 self._add(r'\clip (%s, %s) rectangle (%s, %s);' % (xmin, ymin, xmax, ymax))
97
98 if feuille.afficher_quadrillage:
99 # TODO: style, epaisseur, couleur
100 # Créer des dictionnaires convertir style et epaisseur.
101
102 for (xpas, ypas), style, epaisseur, couleur in feuille.quadrillages:
103 xpas = xpas or xgradu
104 ypas = ypas or ygradu
105 self._draw('(%s, %s) grid (%s, %s)' % (xmin, ymin, xmax, ymax),
106 options=['xstep=%s' % xpas, 'ystep=%s' % ypas,
107 self._style_trait(style),
108 'color=%s' % self._couleur(couleur),
109 'line width=%s' % self._epaisseur(epaisseur)])
110 if feuille.afficher_axes:
111 self._draw([(xmin, 0), (xmax, 0)], arrow=True)
112 self._draw([(0, ymin), (0, ymax)], arrow=True)
113 # TODO: support des vecteurs i et j
114 options = ['thick']
115 self._draw('(0, 0) node[below left] {$%s$}' % origine, options)
116 self._draw('(%s, 2pt) -- (%s, -2pt)' % (xgradu, xgradu), options,
117 node='[below] {$%s$}' % abscisse)
118 self._draw('(2pt, %s) -- (-2pt, %s)' % (ygradu, ygradu), options,
119 node='[left] {$%s$}' % ordonnee)
120
121 def _export_Objet(self, objet, **options):
122 print("Warning: type d'objet non supporté pour l'instant : "
123 + str(objet.__class__.__name__))
124 return ''
125
126 def _export_Point_generique(self, P, **options):
127 # 1.8 : coefficient purement empirique...!
128 r = 1.8*P.etiquette.style('_rayon_')
129 a = P.etiquette.style('_angle_')*180/pi
130 # TODO: gérer style du point
131 self._draw([P], node=r'(%s) {\small $\bullet$}' % P.nom)
132 self._add(r'\path (%s) ++(%s:%s pt) node (%s_etiquette) {%s};'
133 % (P.nom, a, r, P.nom, P.label()))
134 #~ \path (A) ++(30:2) node (B) [draw,fill=blue!20] {B};
135 #~ \node at (1,0) [label={[shift={(1.0,0.3)}]label}] {Node};
136
137 def _export_Texte_generique(self, txt, **options):
138 self._draw([txt], node='{%s}' % txt.label())
139
140 def _export_Cercle_generique(self, cercle, **options):
141 x, y = cercle.centre
142 self._draw('(%s, %s) circle (%s)' % (x, y, cercle.rayon), **cercle.style())
143
144 def _export_Polygone_generique(self, poly, **options):
145 self._draw(poly.points, **poly.style())
146
147 def _export_Segment(self, segment, **options):
148 self._draw(segment.extremites, **segment.style())
149
150 def _export_Droite_generique(self, droite, **options):
151 points = droite._points_extremes()
152 if len(points) == 2:
153 # Sinon, la droite ne coupe pas la fenêtre (ou seulement en un point)
154 self._draw(points, **droite.style())
155
156 def _export_Courbe(self, courbe, **options):
157 # TODO: gérer les extrémités de courbe (points, arc de cercle)
158 xmin, xmax, ymin, ymax = courbe.feuille.fenetre_reellement_affichee()
159 fonction = courbe.fonction
160 x = fonction.variable
161 liste_fx = fonction.expression.split('|')
162 liste_Df = fonction.ensemble.split('|')
163
164 RE_VAR = compile(r'(?<!\w)(%s)(?!\w)' % x)
165 x_ = '\\' + x
166 for (fx, Df) in zip(liste_fx, liste_Df):
167 Df = conversion_chaine_ensemble(Df)
168 fx = traduire_formule(fx)
169 if '**' in fx or '^' in fx:
170 # TODO: gérer les parenthèses imbriquées : (x(x+1))**2
171 def conv(m):
172 return 'pow(%s, %s)' % (m.group('a') or m.group('A'), m.group('b') or m.group('B'))
173 RE_POW = r'((?P<a>%s)|(?P<A>\([^)]+\)))(\^|\*\*)((?P<b>%s)|\((?P<B>[^)]+)\))' \
174 % (NBR_SIGNE_OR_VAR, NBR_SIGNE_OR_VAR)
175 fx = sub(RE_POW, conv, fx)
176 fx = sub(RE_VAR, x_, fx)
177 for I in Df.intervalles:
178 xm = float(max(xmin, I.inf))
179 xM = float(min(xmax, I.sup))
180 self._draw(r'plot ({%s}, {%s})' % (x_, fx),
181 options=['domain=%s:%s,smooth,samples=500,variable=%s,restrict y to domain={%s:%s}' % (xm, xM, x_, float(ymin), float(ymax))],
182 **courbe.style())
183 for val, symb in Df.extremites(xmin, xmax):
184 if symb == '.':
185 self._draw(r'(%s, %s) node {\small$\bullet$}', **courbe.style())
186 else:
187 print("Warning: extrémité de courbe non générée\n"
188 "(extrémité de type %s non géré pour l'instant)." % repr(symb))
189
190 def _export_Vecteur(self, vecteur, **options):
191 A, B = vecteur.extremites
192 self._draw(vecteur.extremites, node='[midway] {%s}' % vecteur.label(),
193 options=['auto=right'], arrow=True, **vecteur.style())