Debian Codegraph @

wxgeometrie/modules/probabilites/arbre.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 from .repetition import repetition_experiences
3
4 # TODO: sortir DialogRepetition de repetition_experiences.py -> __init__.py
5 # pour que repetition_experiences.py n'importe plus pyQt (risque de ralentir l'import pour ptyx !)
6
7 def parse_text(text):
8 """Describe drawing.
9
10 Coordinates are expressed as percentages of picture dimensions.
11 Return a dict containing 2 lists:
12 * one for points: [(text, x, y), ...]
13 * one for lines: [(text, xy1, xy2), ...]
14 """
15 lines = [l for l in text.split("\n") if l.strip()]
16
17 if not lines:
18 return {'points': [], 'lines': []}
19
20 if lines[0].startswith("|"):
21 legende = lines.pop(0)
22 # On réserve de la place pour la légence
23 ymax = 90
24 else:
25 legende = None
26 ymax = 100
27
28 if not lines:
29 return {'points': [], 'lines': []}
30
31 # Répétition d'expériences aléatoires indépendantes
32 #
33 # Ex:
34 # >> A: 1/3
35 # >> &A: 2/3
36 #
37 # équivaut à:
38 #
39 # > A_1: 1/3
40 # >> A_2: 1/3
41 # >> &A_2: 2/3
42 # > &A_1: 2/3
43 # >> A_2: 1/3
44 # >> &A_2: 2/3
45
46 if lines[0].startswith('>>'):
47 profondeur = len(lines[0]) - len(lines[0].lstrip('>'))
48 evenements = {}
49 for line in lines:
50 assert line.startswith(profondeur*'>')
51 nom, proba = line[profondeur:].split(':')
52 evenements[nom.strip()] = proba.strip()
53 lines = repetition_experiences(_profondeur=profondeur, _numeroter=True, **evenements).split('\n')
54
55 # La 1re ligne doit correspondre au 1er embranchement, c'est-à-dire à l'univers (Omega en général).
56 # À défaut, on met un ligne vide (pas de nom au 1er embranchement donc).
57 if lines[0].startswith(">"):
58 lines = [""] + lines
59
60 depths = [len(line) - len(line.lstrip(">")) for line in lines]
61
62 nbr_colonnes = 1 + max(depths, default=0)
63
64 # Nbr de lignes pour chaque colonne.
65 nbr_lignes = []
66
67 for i in xrange(nbr_colonnes):
68 nbr_lignes.append(depths.count(i))
69
70 #intersection, union : \cap \cup
71
72 # Interprétation des lines sous forme de listes de listes
73 # >A
74 # >>B
75 # >>C
76 # >D
77 # >>E
78 # >>>F
79 # >>>G
80 # >>H
81 # >E
82 # devient :
83 # [{'liste': [{'liste': [{'liste': [], 'texte': u'B'}, {'liste': [], 'texte': u'C'}], 'texte': u'A'}, {'liste': [{'liste': [{'liste': [], 'texte': u'F'}, {'liste': [], 'texte': u'G'}], 'texte': u'E'}, {'liste': [], 'texte': u'H'}], 'texte': u'D'}, {'liste': [], 'texte': u'E'}], 'texte': ''}]
84
85 arbre = []
86 ligne_precedente = [-1 for i in xrange(nbr_colonnes)] # numéro de ligne atteint pour chaque colonne
87 for line in lines:
88 colonne = len(line) - len(line.lstrip(">"))
89 branche = arbre
90 for i in xrange(colonne): # on se déplace de branche en branche ;)
91 branche = branche[ligne_precedente[i]]["liste"]
92 branche.append({"texte": line.lstrip(">"), "liste": []})
93 ligne_precedente[colonne] += 1
94 for i in xrange(colonne + 1, nbr_colonnes):
95 ligne_precedente[i] = -1
96 print (arbre)
97
98 # on parcourt l'arbre pour compter le nombre de ramifications
99
100 def compter_ramifications(branche):
101 if len(branche["liste"]) > 0:
102 return sum(compter_ramifications(tige) for tige in branche["liste"])
103 else:
104 return 1
105
106 ramifications = sum(compter_ramifications(branche) for branche in arbre)
107 if param.debug:
108 print("Nombre de ramifications: " + str(ramifications))
109
110 def formater_texte(texte):
111 if texte:
112 if texte.startswith("&"):
113 texte = r"\overline{" + texte[1:] + "}"
114 texte = texte.replace("&", r"\overline ")
115 # P(\overline A) -> P(\overline{A})
116 texte = re.sub("(\\\\overline)[ ]+(%s)" % VAR, lambda m:'%s{%s}' % (m.group(1), m.group(2)), texte)
117 texte = "$" + texte + "$" if texte[0] != '$' else texte
118 if param.latex:
119 texte = "$" + texte + "$" # passage en mode "display" de LaTeX
120 texte = texte.replace(" inter ", r"\ \cap \ ").replace(" union ", r"\ \cup \ ").replace("Omega", r"\Omega").replace("omega", r"\Omega")
121 if param.latex: # on remplace les fractions. Ex: "1/15" -> "\frac{1}{15}"
122 texte = re.sub("[0-9]+/[0-9]+",lambda s:"\\frac{" + s.group().replace("/", "}{") + "}", texte)
123 return texte
124
125
126 def creer_point(x, y, texte):
127 texte = formater_texte(texte)
128 M = Point(x, y, style = "o", couleur = "w", taille = 0)
129 M.label(texte)
130 M.etiquette.style(_rayon_=0, niveau=15, alignement_vertical="center",
131 alignement_horizontal="center", fond=True,
132 couleur_fond="w")
133 return M
134
135
136 def creer_segment(point1, point2, texte):
137 texte = formater_texte(texte)
138 s = Segment(point1, point2)
139 s.label(texte)
140 style = {'_rayon_': 0, 'niveau': 15}
141 placement = self.param('placement_probabilites')
142 if placement == 'dessus':
143 style.update(alignement_vertical='center', couleur_fond='w',
144 fond=True, alignement_horizontal='center',
145 angle=0)
146 elif placement == 'longe':
147 style.update(alignement_vertical='auto', fond=False,
148 alignement_horizontal='center', angle='auto')
149 elif placement == 'decale':
150 style.update(alignement_vertical='auto', fond=False,
151 alignement_horizontal='right', angle=0)
152 else:
153 print(u"Placement: mode '%s' non reconnu." % placement)
154 s.etiquette.style(**style)
155 return s
156
157 ramification = [0] # astuce pour avoir un "objet modifiable" (a mutable object)
158 def parcourir_branche(branche, n, ramification = ramification):
159 txt = branche["texte"].rsplit(":", 1)
160 if len(txt) == 2:
161 txt_pt, txt_segm = txt
162 else:
163 txt_pt = txt[0]
164 txt_segm = ""
165 if len(branche["liste"]) > 0:
166 l = []
167 for tige in branche["liste"]:
168 l.append(parcourir_branche(tige, n + 1))
169
170 M = creer_point(n/(nbr_colonnes - 1), .5*(l[0][0].ordonnee+l[-1][0].ordonnee), txt_pt)
171 self.feuille_actuelle.objets.add(M)
172 for point, txt_s in l:
173 s = creer_segment(M, point, txt_s)
174 self.feuille_actuelle.objets.add(s)
175 return M, txt_segm
176 else:
177 if ramifications > 1:
178 y = 1 - ramification[0]/(ramifications - 1)
179 else:
180 y = .5
181 M = creer_point(n/(nbr_colonnes - 1), y, txt_pt)
182 ramification[0] += 1
183 self.feuille_actuelle.objets.add(M)
184 return M, txt_segm
185
186 for branche in arbre:
187 parcourir_branche(branche, 0)
188
189 if legende is not None:
190 decalage = -0.5
191 for i in legende:
192 if i != "|":
193 break
194 decalage += .5
195 legende = legende.strip("|").split("|")
196 for n in xrange(len(legende)):
197 t = Texte(legende[n], (n + decalage)/(nbr_colonnes - 1), 1.1)
198 self.feuille_actuelle.objets.add(t)
199
200 self.feuille_actuelle.interprete.commande_executee()