-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNet.php
310 lines (288 loc) · 12.3 KB
/
Net.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
if (realpath($_SERVER['SCRIPT_FILENAME']) != realpath(__FILE__)); // file is include do nothing
else if (php_sapi_name() == "cli") {
Dramagraph_Net::cli();
}
/*
" Graphe d’interlocution <i>(cliquez ici pour plus d’explications)</i></summary>
<p>Ce graphe est généré automatiquement à partir du texte balisé de la pièce de théâtre. Chaque pastille est un personnage, dont la taille est proportionnelle à la quantité de paroles qui lui sont attribuées. Les flèches indiquent à qui s’adresse ces paroles. Le placement des pastilles résulte d’un algorithme automatique cherchant à éviter les croisements entre les flèches. Jouer avec les boutons ci-dessous, notamment le mélange aléatoire (♻) et la relance de l’algorithme (►), permet de mieux saisir ce qui est arbitraire, ou déterminé par le poids des paroles, dans la disposition relative des pastilles. Les couleurs sont des convenances facilitant la lecture, elles résultent d’une combinatoire entre sexe, âge, et statut des personnages. Retrouvez <a href="#tables">ci-dessous</a> les tables de données avec lesquelles l’image est produite.</p>
";
Pinche en un disco para desplazarlo. Clic derecho para borrarlo.
S’il est possible de traduire pour les tables en bas :
Tabla de roles
Estadísticas por relación
*/
/**
* Visualisation relatives au réseaux de parole
*/
class Dramagraph_Net
{
/** Couleurs pour le graphe, la clé est une classe de nœud, les valeurs son 1: nœud, 2: lien */
public static $colors = array(
1 => array("#FF4C4C", "rgba(255, 0, 0, 0.5)"),
2 => array("#A64CA6", "rgba(128, 0, 128, 0.5)"),
3 => array("#4C4CFF", "rgba(0, 0, 255, 0.5)"),
4 => array("#4c4ca6", "rgba(0, 0, 128, 0.5)"),
5 => array("#A6A6A6", "rgba(140, 140, 160, 0.6)"),
"superior" => array("#333333", "rgba(00, 00, 00, 0.3)"),
"inferior" => array("#A0A0A0", "rgba(96, 96, 96, 0.3)"),
"female" => array("#FF4C4C", "rgba(255, 0, 0, 0.5)"),
"female superior" => array("#FF0000", "rgba(255, 0, 0, 0.5)"),
"female junior" => array("#FFb0D0", "rgba(255, 128, 192, 0.5)"),
"female inferior" => array("#D07070", "rgba(192, 96, 96, 0.3)"),
"female veteran" => array("#903333", "rgba(128, 0, 0, 0.3)"),
"male" => array("#4C4CFF", "rgba(0, 0, 255, 0.3)"),
"male junior" => array("#B0D0FF", "rgba(128, 192, 255, 0.5)"),
"male veteran" => array("#333390", "rgba(0, 0, 128, 0.3)"),
"male superior" => array("#0000FF", "rgba(0, 0, 255, 0.3)"),
"male inferior" => array("#C0C0EE", "rgba(96, 96, 192, 0.3)"),
"male exterior" => array("#A0A0A0", "rgba(96, 96, 192, 0.3)"),
);
/**
* Write the graph html
*/
public static function graph( $pdo, $playcode )
{
$play = $pdo->query("SELECT * FROM play where code = ".$pdo->quote($playcode))->fetch();
$role = $pdo->query("SELECT * FROM role WHERE play = ".$play['id']." ORDER BY c DESC LIMIT 1")->fetch();
$html = array();
$id = 'graph_'.$playcode;
$html[] = self::canvas( $id );
$html[] = '<script> (function () { var data =';
$html[] = self::sigma( $pdo, $playcode );
// , '.( ceil($role['c']/900) ).' ne plus fixer la taille maximale du nœud selon la taille du texte
$html[] = ' var graph = new Rolenet("'.$id.'", data ); //';
$html[] = " })(); </script>\n";
return implode("\n", $html);
}
/**
* Html for canvas
*/
public static function canvas($id='graph')
{
// <div class="sans-serif" style="position: absolute; top: 0; left: 1ex; font-size: 70%; ">Cliquer un nœud pour le glisser-déposer. Clic droit pour le supprimer</div>
$html = '
<div id="'.$id.'" class="graph" oncontextmenu="return false">
<div style="position: absolute; bottom: 0; right: 2px; z-index: 2; ">
<button class="colors but" title="Gris ou couleurs">◐</button>
<button class="shot but" type="button" title="Prendre une photo">📷</button>
<button class="turnleft but" type="button" title="Rotation vers la gauche">⤴</button>
<button class="turnright but" type="button" title="Rotation vers la droite">⤵</button>
<button class="zoomin but" style="cursor: zoom-in; " type="button" title="Grossir">+</button>
<button class="zoomout but" style="cursor: zoom-out; " type="button" title="Diminuer">–</button>
<button class="but restore" type="button" title="Recharger">O</button>
<button class="mix but" type="button" title="Mélanger le graphe">♻</button>
<button class="grav but" type="button" title="Démarrer ou arrêter la gravité">►</button>
<span class="resize interface" style="cursor: se-resize; font-size: 1.3em; " title="Redimensionner la feuille">⬊</span>
</div>
</div>
';
return $html;
}
/**
* Json compatible avec la librairie sigma.js
*/
public static function sigma( $pdo, $playcode )
{
// filtrer les nœuds qui sont dans les interludes
$nodes = self::nodes( $pdo, $playcode, 'scene' );
$edges = self::edges( $pdo, $playcode );
$html = array();
$html[] = "{ ";
$html[] = " edges: [";
for ($i=0; $i < count($edges); $i++) {
$edge = $edges[$i];
if (!isset($nodes[$edge['source']])) continue;
if (!isset($nodes[$edge['target']])) continue;
$source = $nodes[$edge['source']];
$col = "";
if (isset(self::$colors[$source['class']])) {
$col = ', color: "'.self::$colors[$source['class']][1].'"';
}
else if (isset(self::$colors['role'.$i])) {
$col = ', color: "'.self::$colors[$source['rank']][1].'"';
}
$html[] = ' {id:"e'.$i.'", source:"'.$edge['source'].'", target:"'.$edge['target'].'", size:"'.$edge['c'].'"'.$col.', type:"drama"},';
}
$html[] = " ],";
$html[] = " nodes: [";
$count = count($nodes);
$i = 1;
foreach ($nodes as $code=>$node) {
if (!$code) continue;
/*
// position initiale en cercle, à 1h30
$angle = -M_PI - (M_PI*2/$count) * ($i-1);
// $angle = 2*M_PI/$count * ($i -1);
$x = number_format( 6.0*cos($angle), 4 );
$y = number_format( 6.0*sin($angle), 4 );
*/
// position initiale en ligne horizontale, pour éloigner à droire les pers secondaires
// $x = $i ;
if ( $node['sex'] == 2 ) $y = -0.5*$count ;
else if ( $node['sex'] == 1 ) $y = 0.5 * $count;
else $y = 0.1 * ($i % 2); // légère variation si rien
// if ( $node['status'] == 'inferior' ) $x = 2*$x;
$x=$i;
$col = "";
if (isset(self::$colors[$node['class']])) {
$col = ', color: "'.self::$colors[$node['class']][0].'"';
}
else if (isset(self::$colors['role'.$i])) {
$col = ', color: "'.self::$colors[$node['class']][0].'"';
}
// $json_options = JSON_UNESCAPED_UNICODE; // incompatible 5.3
$json_options = null;
$html[] = " {id:'".$node['code']."', label:".json_encode($node['label'], $json_options).", size:".(0+$node['c']).", x:". number_format ($x, 1, '.', '').", y: ".number_format ($y, 1, '.', '').$col.", title: ".json_encode($node['title'], $json_options).', type:"drama"},';
$i++;
}
$html[] = " ]";
$html[] = "};";
return implode("\n", $html);
}
/**
* Produire fichier de nœuds et de relations
* TODO, à vérifier
*/
public static function gephi( $pdo, $playcode )
{
$data = self::nodes( $pdo, $playcode, 'act' );
$f = $playcode.'-nodes.csv';
$w = fopen($f, 'w');
fwrite($w, "Id,Label,Weight\n");
foreach ( $data as $key => $row ) {
fwrite($w, $key.",".$row['label'].",".$row['c']."\n");
}
fclose($w);
echo $f.' ';
$data = self::edges( $pdo, $playcode, 'act' );
$f = $playcode.'-edges.csv';
$w = fopen($f, 'w');
fwrite($w, "Source,Target,Weight\n");
foreach ( $data as $key => $row ) {
fwrite($w, $row['source'].",".$row['target'].",".$row['c']."\n");
}
fclose($w);
echo $f."\n";
}
/**
* Liste de nœuds, pour le graphe, on filtre selon le type d'acte
*/
public static function nodes( $pdo, $playcode, $scenetype=null )
{
$play = $pdo->query("SELECT * FROM play where code = ".$pdo->quote($playcode))->fetch();
$data = array();
$rank = 1;
$qtype = $pdo->prepare("SELECT scene.* FROM presence, configuration, scene WHERE scene.type = ? AND presence.role = ? AND presence.configuration = configuration.id AND configuration.scene = scene.id ");
// vérifier que le type de scene existe (pb pour les pièce avec juste des actes)
$qcount = $pdo->prepare( "SELECT count(*) FROM scene WHERE play = ? AND type = ?");
$qcount->execute(array( $play['id'], $scenetype) );
list( $count ) = $qcount->fetch();
if ( !$count ) $scenetype = null;
foreach ($pdo->query("SELECT * FROM role WHERE role.play = ".$play['id']." ORDER BY role.ord") as $role) {
// role invisible dans les configurations
if (!$role['sources']) continue;
if ( $scenetype ) {
$qtype->execute(array($scenetype, $role['id']));
if (!$qtype->fetch()) continue;
}
$class = "";
if ($role['sex'] == 2) $class = "female";
else if ($role['sex'] == 1) $class = "male";
if ($role['status'] == 'exterior') $class .= " exterior";
else if ($role['status'] == 'inferior') $class .= " inferior";
else if ($role['status'] == 'superior') $class .= " superior";
else if ($role['age'] == 'junior') $class .= " junior";
else if ($role['age'] == 'veteran') $class .= " veteran";
$role['class'] = trim($class);
$role['rank'] = $rank;
$data[$role['code']] = $role;
$rank++;
}
return $data;
}
/**
* Relations paroles entre les rôles
*/
public static function edges( $pdo, $playcode )
{
$play = $pdo->query("SELECT * FROM play where code = ".$pdo->quote($playcode))->fetch();
// load a dic of rowid=>code for roles
$cast = array();
foreach ($pdo->query( "SELECT id, code, label, c FROM role WHERE play = ".$play['id'], PDO::FETCH_ASSOC ) as $row) {
$cast[$row['id']] = $row;
}
$sql = "SELECT
edge.source,
edge.target,
count(sp) AS sp,
sum(sp.c) AS c,
count(DISTINCT sp.configuration) AS confs,
(SELECT c FROM role WHERE edge.source=role.id)+(SELECT c FROM role WHERE edge.target=role.id) AS sort
FROM edge, sp
WHERE edge.play = ? AND edge.sp = sp.id
GROUP BY edge.source, edge.target
ORDER BY sort DESC
";
$q = $pdo->prepare($sql);
$q->execute(array($play['id']));
$data = array();
$max = false;
$nodes = array();
$i = 1; // more
while ($row = $q->fetch()) {
if(!isset($cast[$row['source']])) continue; // sortie de la liste des rôles
if(!isset($cast[$row['target']])) continue; // sortie de la liste des rôles
if(!$max) $max = $row['c'];
/*
$dothreshold = false; // no threshold
if ($sp['source']==$sp['target']);
else if (!isset($nodes[$sp['source']])) {
$nodes[$sp['source']] = 1;
$dothreshold = false;
}
else {
$nodes[$sp['source']]++;
}
if ($sp['source']==$sp['target']);
else if (!isset($nodes[$sp['target']])) {
$nodes[$sp['target']] = 1;
$dothreshold = false;
}
else {
$nodes[$sp['target']]++;
}
// a threshold, to apply only on relation already linked to the net
if ($dothreshold && ( $sp['ord'] <100 || ($sp['ord']/$play['c']) < 0.01) ) {
continue;
}
*/
$i++;
$data[] = array(
'no' => $i,
'sort' => 0+$row['sort'],
'source' => $cast[$row['source']]['code'],
'slabel' => $cast[$row['source']]['label'],
'target' => $cast[$row['target']]['code'],
'tlabel' => $cast[$row['target']]['label'],
'c' => $row['c'],
'sp' => $row['sp'],
'confs' => $row['confs'],
);
}
return $data;
}
static function cli() {
$usage = '
usage : php -f '.basename(__FILE__).' base.sqlite auteur_titre '."\n\n";
$timeStart = microtime(true);
array_shift($_SERVER['argv']); // shift first arg, the script filepath
if (!count($_SERVER['argv'])) exit($usage);
$sqlite = array_shift($_SERVER['argv']);
$pdo = new PDO('sqlite:'.$sqlite);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$playcode = array_shift($_SERVER['argv']);
self::gephi( $pdo, $playcode );
}
}
?>