Révision 37

tmp/org.txm.progression.core/src/org/txm/progression/core/functions/Progression2.java (revision 37)
1
// Copyright © 2010-2013 ENS de Lyon.
2
// Copyright © 2007-2010 ENS de Lyon, CNRS, INRP, University of
3
// Lyon 2, University of Franche-Comté, University of Nice
4
// Sophia Antipolis, University of Paris 3.
5
// 
6
// The TXM platform is free software: you can redistribute it
7
// and/or modify it under the terms of the GNU General Public
8
// License as published by the Free Software Foundation,
9
// either version 2 of the License, or (at your option) any
10
// later version.
11
// 
12
// The TXM platform is distributed in the hope that it will be
13
// useful, but WITHOUT ANY WARRANTY; without even the implied
14
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15
// PURPOSE. See the GNU General Public License for more
16
// details.
17
// 
18
// You should have received a copy of the GNU General
19
// Public License along with the TXM platform. If not, see
20
// http://www.gnu.org/licenses.
21
// 
22
// 
23
// 
24
// $LastChangedDate: 2016-09-19 10:31:00 +0200 (Mon, 19 Sep 2016) $
25
// $LastChangedRevision: 3298 $
26
// $LastChangedBy: mdecorde $ 
27
//
28
package org.txm.progression.core.functions;
29

  
30
import java.io.BufferedWriter;
31
import java.io.File;
32
import java.io.FileOutputStream;
33
import java.io.IOException;
34
import java.io.OutputStreamWriter;
35
import java.util.ArrayList;
36
import java.util.HashMap;
37
import java.util.List;
38
import java.util.Map;
39

  
40
import org.txm.HasResults;
41
import org.txm.Messages;
42
import org.txm.functions.Function;
43
import org.txm.functions.TXMResult;
44
import org.txm.searchengine.cqp.clientExceptions.CqiClientException;
45
import org.txm.searchengine.cqp.corpus.Corpus;
46
import org.txm.searchengine.cqp.corpus.CorpusManager;
47
import org.txm.searchengine.cqp.corpus.Property;
48
import org.txm.searchengine.cqp.corpus.QueryResult;
49
import org.txm.searchengine.cqp.corpus.StructuralUnit;
50
import org.txm.searchengine.cqp.corpus.StructuralUnitProperty;
51
import org.txm.searchengine.cqp.corpus.Subcorpus;
52
import org.txm.searchengine.cqp.corpus.query.Match;
53
import org.txm.searchengine.cqp.corpus.query.Query;
54
import org.txm.searchengine.cqp.serverException.CqiServerError;
55

  
56
/**
57
 * Computes a progression similar to the progression of Weblex software.
58
 *  
59
 * @author mdecorde
60
 * @author sjacquot
61
 */
62
public class Progression2 extends Function implements TXMResult  {
63

  
64
	/** The corpus. */
65
	Corpus corpus;
66

  
67
	/** The queries. */
68
	List<Query> queries;
69

  
70
	/** The structure. */
71
	StructuralUnit structure;
72

  
73
	/** The property. */
74
	StructuralUnitProperty property;
75

  
76
	/** The propertyregex. */
77
	String propertyRegex;
78

  
79
	/** The Xmin corpus. */
80
	int XminCorpus;
81

  
82
	/** The Xmax corpus. */
83
	int XmaxCorpus;
84
	
85
	/** The writer. */
86
	private BufferedWriter writer;
87

  
88
	@Deprecated
89
	// FIXME : to remove when charts engine will be validated, related to rendering system
90
	public static String black = "black"; //$NON-NLS-1$
91

  
92
	/** The colors. */
93
	@Deprecated
94
	// FIXME : to remove when charts engine will be validated, related to rendering system
95
	public static String[] colors = {"red","blue","green3","gold", "deeppink1", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
96
		"firebrick","navyblue","green4", "darkgoldenrod1","magenta1", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
97
		"deepskyblue","green","yellow","cyan","greenyellow", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
98
		"seagreen1", black, "grey" }; //$NON-NLS-1$ //$NON-NLS-2$ 
99
	//int[] colors16 = {552, 26, 257, 142, 117,133 ,491, 258, 76, 451, 121, 254, 652, 68 ,259, 575};
100

  
101
	/** The monocolors. */
102
	@Deprecated
103
	// FIXME : to remove when charts engine will be validated, related to rendering system
104
	public static String[] monocolors = {black, black, black, black, black,
105
		black, black, black, black, black,
106
		black, black, black, black, black, black }; 
107
	//int[] monocolors = {24, 24, 24, 24, 24, 24 ,24, 24, 24, 24, 24, 24, 24, 24 ,24, 24};
108

  
109
	// jeu de 16 couleurs :
110

  
111
	// jeu de 10 couleurs :
112
	@Deprecated
113
	// FIXME : to remove when charts engine will be validated, related to rendering system
114
	public static String[] colors10 = {"red","blue","green4","gold","deeppink1", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
115
			"firebrick", "deepskyblue","greenyellow", "darkgoldenrod1","magenta1"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
116

  
117
	// jeu de 5 couleurs :
118
	@Deprecated
119
	// FIXME : to remove when charts engine will be validated, related to rendering system
120
	public static String[] colors5 = {"red", "blue", "green4", "gold", "deeppink1"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
121

  
122
	/** The styles. */
123
	@Deprecated
124
	// FIXME : to remove when charts engine will be validated, related to rendering system
125
	public static int[] styles = {
126
		1, 2, 3, 4, 5, 6, 1, 2, 3, 4 ,5, 6 ,1 ,2 ,3, 4 }; 
127

  
128
	/** The monostyles. */
129
	@Deprecated
130
	// FIXME : to remove when charts engine will be validated, related to rendering system
131
	public static int[] monostyles = {
132
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1 ,1 ,1, 1, 1, 1 }; 
133

  
134

  
135
	/** The widths. */
136
	@Deprecated
137
	// FIXME : to remove when charts engine will be validated, related to rendering system
138
	public static int[] widths = {
139
		1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3 }; 
140

  
141
	/** The monowidths. */
142
	@Deprecated
143
	// FIXME : to remove when charts engine will be validated, related to rendering system
144
	public static int[] monowidths = {
145
		1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; 
146

  
147

  
148
	/** List of token position in the text. */
149
	List<int[]> allPositions = new ArrayList<int[]>();
150

  
151
	/** The structurepositions. */
152
	int[] structurePositions = new int[0];
153

  
154
	/** The structurenames. */
155
	String[] structureNames = new String[0];
156

  
157
	/** graph boundaries. */
158
	int maxY;
159

  
160
	/** The max x. */
161
	int maxX;
162

  
163
	/** The name. */
164
	String name;
165

  
166
	/** The repeatvalues. */
167
	private boolean repeatvalues;
168

  
169
	/** The bande. */
170
	private float bande = 0.0f;
171

  
172
	/** The bandemultiplier. */
173
	private float bandemultiplier;
174

  
175
	/**
176
	 * Instantiates a new progression.
177
	 *
178
	 * @param corpus the corpus
179
	 * @param queries , a curve per query
180
	 * @param structure , the structural unit to show
181
	 * @param property , the value to display
182
	 * @param propertyregex , a selection of the values to display
183
	 * @param doCumulative , if true do a cumulative graph, if not compute the density (R
184
	 * function)
185
	 * @param monochrome the monochrome
186
	 * @param monostyle the monostyle
187
	 * @param linewidth the linewidth
188
	 * @param repeat the repeat
189
	 * @param bandemultiplier the bandemultiplier
190
	 */
191
	@Deprecated
192
	// FIXME : to remove when charts engine will be validated
193
	// FIXME : all parameters related to rendering should removed from this class and centralized in the charts engine system
194
	public Progression2(Corpus corpus, List<Query> queries,
195
			StructuralUnit structure, StructuralUnitProperty property,
196
			String propertyregex, boolean doCumulative, int linewidth, boolean repeat, float bandemultiplier) {
197
		//System.out.println("monochrome: "+monochrome+" monostyle: "+monostyle+" width: "+linewidth);
198
		this.corpus = corpus; // the corpus which we compute on
199
		this.queries = queries; // the query of the selection
200
		this.structure = structure;
201
		this.property = property;
202
		this.propertyRegex = propertyregex;
203
		this.repeatvalues = repeat;
204
		this.bandemultiplier = bandemultiplier;
205

  
206
		for (int i = 0 ; i < monowidths.length ; i++) {
207
			monowidths[i] = linewidth;
208
		}
209
	}
210

  
211
	/**
212
	 * Compute.
213
	 *
214
	 * @return true, if successful
215
	 * @throws CqiClientException the cqi client exception
216
	 * @throws CqiServerError 
217
	 * @throws IOException 
218
	 */
219
	public boolean process() throws CqiClientException, IOException, CqiServerError {
220
		return stepQueries() && stepStructuralUnits() && stepFinalize();
221
	}
222

  
223
	/**
224
	 * Test discontinuity of a corpus. If the corpus is a subcorpus then test if the start-end of matches make no hole
225
	 * @param corpus
226
	 * @return
227
	 */
228
	public static boolean canRunProgression(Corpus corpus) {
229
		//System.out.println(corpus.getMatches());
230
		if (corpus.getMatches().size() == 1) return true;
231
		else {
232
			Match previousMatch = null;
233
			for (Match m : corpus.getMatches()) {
234
				if (previousMatch == null) {
235
					previousMatch = m;
236
					continue;
237
				}
238
				
239
				if (m.getStart() == previousMatch.getEnd()+1) {
240
					previousMatch = m;
241
					continue;
242
				} else {
243
					return false;
244
				}
245
			}
246
		}
247
		return true;
248
	}
249

  
250
	/**
251
	 * Step queries.
252
	 *
253
	 * @throws CqiClientException the cqi client exception
254
	 */
255
	public boolean stepQueries() throws CqiClientException
256
	{
257
		maxX = corpus.getSize();
258
		int npositions = 0;
259
		for (Query query : queries) {
260
			// System.out.println("query  "+query.getQueryString());
261
			QueryResult result = corpus.query(query, query.getQueryString()
262
					.replace(" ", "_") + "_progression", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$			
263
			int nLines = result.getNMatch();
264
			if (maxY < nLines)
265
				maxY = nLines;
266

  
267
			List<Match> matches = null;
268
			if (nLines > 0) {
269
				matches = result.getMatches(0, nLines - 1); // get the indexes
270
				// sequences of result's tokens
271
			} else {
272
				matches = new ArrayList<Match>();
273
			}
274
			//System.out.println("matches: "+matches);
275
			int[] positions = new int[matches.size()];
276
			// System.out.println("nb positions "+matches.size());
277
			// if (matches.size() > 0)
278
			allPositions.add(positions);
279
			int i = 0;
280
			for (Match m : matches) {
281
				positions[i++] = m.getStart();
282
				npositions++;
283
			}
284
			result.drop();
285
		}
286
		return npositions > 0;
287
	}
288

  
289
	/**
290
	 * Step structural units.
291
	 *
292
	 * @throws CqiClientException the cqi client exception
293
	 * @throws CqiServerError 
294
	 * @throws IOException 
295
	 */
296
	public boolean stepStructuralUnits() throws CqiClientException, IOException, CqiServerError
297
	{
298
		// structure query
299
		if (structure != null) {
300
			Query query = new Query("<" + structure.getName() + ">[]"); //$NON-NLS-1$ //$NON-NLS-2$
301
			if (property != null) {
302
				query = new Query("<" + property.getFullName() + ">[]"); //$NON-NLS-1$ //$NON-NLS-2$
303
				if (propertyRegex != null)
304
					query = new Query(
305
							"<"	+ property.getFullName() + "=\"" + propertyRegex + "\">[]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
306
			}
307

  
308
			// System.out.println("Struct: "+ structure+" property: "+property);
309
			// System.out.println(query.getQueryString());
310
			QueryResult result = corpus.query(query, query.getQueryString()
311
					.replace(" ", "_") + "_progression", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
312
			int[] starts = result.getStarts();
313
			result.drop();
314
			int nLines = starts.length;
315
			
316
//			List<Match> matches = new ArrayList<Match>();
317
//			if (nLines > 0)
318
//				matches = result.getMatches(0, nLines - 1); // get the indexes
319
			// sequences of result's tokens
320

  
321
			structurePositions = new int[nLines];
322
			structureNames = new String[nLines];
323

  
324
			
325
			
326
			Map<Property, List<String>> refValues = new HashMap<Property, List<String>>();
327
			if (property != null) {
328
				List<String> values = CorpusManager.getCorpusManager().getCqiClient().getSingleData(property, starts);
329
				refValues.put(property, values);
330
			}
331

  
332
			int i = 0;
333
			String previousname = ""; //$NON-NLS-1$
334
			String currentname = ""; //$NON-NLS-1$
335
			int previousposition = -99999;
336
			int distmin = 999999;
337
			for (int m : starts) {
338
				if (property != null)
339
					currentname = refValues.get(property).get(i);
340
				else
341
					currentname = structure.getName() + i;
342

  
343
				if (repeatvalues) {
344
					structureNames[i] = currentname;
345
					structurePositions[i] = m;
346
				} else {
347
					if (!previousname.equals(currentname)) {
348
						structureNames[i] = currentname;
349
						structurePositions[i] = m;
350
					}
351
				}
352
				if (i == 0)
353
					structurePositions[i] += 1; 
354

  
355
				if (m - previousposition < distmin) {
356
					distmin = m - previousposition;
357
				}
358

  
359
				previousname = ""+currentname; //$NON-NLS-1$
360
				previousposition = m;
361

  
362
				i++;
363
			}
364
			this.bande = distmin*bandemultiplier;
365
		}
366
		return true;
367
	}
368

  
369
	/**
370
	 * Step finalize.
371
	 *
372
	 * @throws CqiClientException the cqi client exception
373
	 */
374
	public boolean stepFinalize() throws CqiClientException
375
	{
376
		if (corpus instanceof Subcorpus) {
377
			List<Match> matches = ((Subcorpus) corpus).getMatches();
378
			if (matches.size() == 0) {
379
				System.out.println(Messages.Progression_1);
380
				return false;
381
			}
382
			
383
			XminCorpus = matches.get(0).getStart();
384
			XmaxCorpus = matches.get(matches.size()-1).getEnd();		
385
		} else {
386
			XminCorpus = 0;
387
			XmaxCorpus = corpus.getSize();
388
		}
389
		//System.out.println("min: "+XminCorpus+ "max: "+XmaxCorpus);
390

  
391
		if (bande <= 0) {
392
			bande = ((XmaxCorpus - XminCorpus)/100)*bandemultiplier;
393
			if (bande == 0)
394
				bande = 1.0f;
395
		}
396
		return true;
397
	}
398

  
399
	/** The norep. */
400
	public static int norep = 1;
401

  
402
	/** The prefix r. */
403
	public static String prefixR = "Progression"; //$NON-NLS-1$
404

  
405

  
406
	/**
407
	 * 
408
	 * @param outfile
409
	 * @param encoding
410
	 * @return
411
	 * @throws IOException
412
	 */
413
	public boolean toTxt(File outfile, String encoding) throws IOException {
414
		// NK: writer declared as class attribute to perform a clean if the operation is interrupted
415
		tryAcquireSemaphore();
416
		this.writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile),
417
				encoding)); 
418
		for (int i = 0 ; i < queries.size() ; i++) {
419
			writer.write("* "+queries.get(i)+"\n"); //$NON-NLS-1$ //$NON-NLS-2$
420
			for (int p : allPositions.get(i)) {
421
				writer.write(""+p+"\n"); //$NON-NLS-1$ //$NON-NLS-2$
422
			}
423
		}
424
		writer.close();
425
		releaseSemaphore();
426
		return true;
427
	}
428
	
429

  
430

  
431

  
432

  
433
	/**
434
	 * Gets the max x.
435
	 *
436
	 * @return the max x
437
	 */
438
	public int getMaxX() {
439
		return maxX;
440
	}
441

  
442
	/**
443
	 * Gets the max y.
444
	 *
445
	 * @return the max y
446
	 */
447
	public int getMaxY() {
448
		return maxY;
449
	}
450

  
451
	/**
452
	 * Gets the corpus.
453
	 *
454
	 * @return the corpus
455
	 */
456
	public Corpus getCorpus() {
457
		return corpus;
458
	}
459

  
460
	/**
461
	 * Gets the queries.
462
	 *
463
	 * @return the queries
464
	 */
465
	public List<Query> getQueries() {
466
		return queries;
467
	}
468

  
469
	/**
470
	 * Gets the allpositions.
471
	 *
472
	 * @return the allpositions
473
	 */
474
	public List<int[]> getAllpositions() {
475
		return allPositions;
476
	}
477

  
478
	/**
479
	 * Gets the positions counts.
480
	 *
481
	 * @return the positions counts
482
	 */
483
	public List<Integer> getPositionsCounts() {
484
		ArrayList<Integer> counts = new ArrayList<Integer>();
485
		for (int[] list : allPositions)
486
			counts.add(list.length);
487
		return counts;
488
	}
489

  
490
	/**
491
	 * Gets the name.
492
	 *
493
	 * @return the name
494
	 */
495
	public String getName() {
496
		return this.queries.toString();
497
	}
498

  
499
	/**
500
	 * Gets the details.
501
	 *
502
	 * @return the details
503
	 */
504
	public String getDetails() {
505
		return this.queries.toString();
506
	}
507

  
508
	
509
	/**
510
	 * Checks if is repeatvalues.
511
	 *
512
	 * @return true, if is repeatvalues
513
	 */
514
	public boolean isRepeatvalues() {
515
		return repeatvalues;
516
	}
517

  
518

  
519

  
520
	@Override
521
	public void clean() {
522
		try {
523
			this.writer.flush();
524
			this.writer.close();	
525
		} catch (IOException e) {
526
			// TODO Auto-generated catch block
527
			org.txm.utils.logger.Log.printStackTrace(e);
528
		}
529
	}
530

  
531
	@Override
532
	public boolean toTxt(File outfile, String encoding, String colseparator,
533
			String txtseparator) throws Exception {
534
		return toTxt(outfile, encoding);
535
	}
536

  
537
	/**
538
	 * @return the allPositions
539
	 */
540
	public List<int[]> getAllPositions() {
541
		return allPositions;
542
	}
543

  
544
	/**
545
	 * @return the structurePositions
546
	 */
547
	public int[] getStructurePositions() {
548
		return structurePositions;
549
	}
550

  
551
	/**
552
	 * @return the structureNames
553
	 */
554
	public String[] getStructureNames() {
555
		return structureNames;
556
	}
557

  
558
	/**
559
	 * @return the structure
560
	 */
561
	public StructuralUnit getStructure() {
562
		return structure;
563
	}
564

  
565
	/**
566
	 * @return the property
567
	 */
568
	public StructuralUnitProperty getProperty() {
569
		return property;
570
	}
571

  
572
	/**
573
	 * @return the propertyRegex
574
	 */
575
	public String getPropertyRegex() {
576
		return propertyRegex;
577
	}
578

  
579
	/**
580
	 * @return the bande
581
	 */
582
	public float getBande() {
583
		return bande;
584
	}
585

  
586
	/**
587
	 * @return the xminCorpus
588
	 */
589
	public int getXminCorpus() {
590
		return XminCorpus;
591
	}
592

  
593
	/**
594
	 * @return the xmaxCorpus
595
	 */
596
	public int getXmaxCorpus() {
597
		return XmaxCorpus;
598
	}
599

  
600

  
601

  
602
	/**
603
	 * @param name the name to set
604
	 */
605
	public void setName(String name) {
606
		this.name = name;
607
	}
608

  
609
	@Override
610
	public String[] getExportTXTExtensions() {
611
		return new String[]{"*.txt"};
612
	}
613

  
614
	@Override
615
	public boolean delete() {
616
		return corpus.removeResult(this);
617
	}
618

  
619
	@Override
620
	public HasResults getParent() {
621
		return corpus;
622
	}
623

  
624
	/**
625
	 * Computes and gets a query constructed from all the queries in alternative mode (with pipe |).
626
	 * @return
627
	 */
628
	public String getQueriesString()	{
629
		ArrayList<Integer> allQueriesIndexes = new ArrayList<Integer>(this.queries.size());
630
		for(int i = 0; i < this.queries.size(); i++) {
631
			allQueriesIndexes.add(i);
632
		}
633
		return this.getQueriesString(allQueriesIndexes) ;
634
	}
635
	
636
	/**
637
	 * Computes and gets a query constructed from all the queries specified by their index in alternative mode (with pipe |).
638
	 * @param queriesIndexes
639
	 * @return
640
	 */
641
	public String getQueriesString(ArrayList<Integer> queriesIndexes)	{
642
		
643
		String query = "";
644
		
645
		for(int i = 0; i < this.queries.size(); i++) {
646
			if(queriesIndexes.contains(i))	{
647
				String tmpQuery = this.queries.get(i).getQueryString();
648
				// Remove "[" and "]" only if it's a simple query as "[look]" 
649
				if(tmpQuery.startsWith("[") && !tmpQuery.contains("="))	{
650
					int length = tmpQuery.length();
651
					if(tmpQuery.endsWith("]"))	{
652
						length--;
653
					}
654
					tmpQuery = tmpQuery.substring(1, length);
655
				}
656
				if(query.length() > 0)	{
657
					query += " | ";
658
				}
659
				query += tmpQuery;
660
			}
661
		}
662

  
663
		return query;
664
		
665
	}
666
}
0 667

  
tmp/org.txm.progression.core/src/org/txm/progression/core/chartsengine/r/RProgressionChartCreator.java (revision 37)
1
package org.txm.progression.core.chartsengine.r;
2

  
3
import java.io.File;
4

  
5
import org.apache.commons.lang.StringEscapeUtils;
6
import org.rosuda.REngine.REXPMismatchException;
7
import org.txm.chartsengine.r.core.RChartCreator;
8
import org.txm.chartsengine.r.core.RChartsEngine;
9
import org.txm.progression.core.chartsengine.base.Utils;
10
import org.txm.progression.core.functions.Progression2;
11
import org.txm.progression.core.preferences.ProgressionPreferences;
12
import org.txm.stat.StatException;
13
import org.txm.stat.engine.r.RWorkspace;
14
import org.txm.stat.engine.r.RWorkspaceException;
15
import org.txm.tbx.preferences.TXMPreferences;
16
import org.txm.utils.logger.Log;
17

  
18
/**
19
 * R progression chart creator.
20
 * @author mdecorde
21
 * @author sjacquot
22
 *
23
 */
24
public class RProgressionChartCreator extends RChartCreator {
25

  
26
	public RProgressionChartCreator() {
27
		// TODO Auto-generated constructor stub
28
	}
29

  
30
	@Override
31
	public Object createChart(Object resultData, String preferencesNode) {
32
		// TODO Auto-generated method stub
33
		return null;
34
	}
35

  
36
	@Override
37
	public File createChartFile(Object resultData, File file, String preferencesNode) {
38

  
39
		try {
40
			
41
			Progression2 progression = (Progression2) resultData;
42
			
43
			// parameters
44
			boolean grayscale = TXMPreferences.getBoolean(preferencesNode, ProgressionPreferences.MONOCHROMATIC);
45
			boolean monostyle = TXMPreferences.getBoolean(preferencesNode, ProgressionPreferences.MONO_STYLE);
46
			boolean cumulative = TXMPreferences.getBoolean(preferencesNode, ProgressionPreferences.CUMULATIVE);
47
			
48
			RWorkspace rw = RWorkspace.getRWorkspaceInstance();
49
			rw.eval("library(textometry)");
50
			// System.out.println("create list of positions");
51
			String listString = "list("; //$NON-NLS-1$
52
			for(int i = 0; i < progression.getAllpositions().size(); i++) {
53
				int[] positions = progression.getAllpositions().get(i);
54
				// System.out.println("add vector "+i);
55
				rw.eval("rm(x" + i + ")"); //$NON-NLS-1$ //$NON-NLS-2$
56
				rw.addVectorToWorkspace("x" + i, positions); //$NON-NLS-1$
57
				listString += "x" + i + ","; //$NON-NLS-1$ //$NON-NLS-2$
58
			}
59
			listString = listString.substring(0, listString.length() - 1) + ")"; //$NON-NLS-1$
60
			// System.out.println("create positions");
61
			rw.eval("rm(positions)"); //$NON-NLS-1$
62
			rw.eval("positions <- " + listString); //$NON-NLS-1$
63

  
64
			rw.eval("rm(structurepositions)"); //$NON-NLS-1$
65
			rw.addVectorToWorkspace("structurepositions", progression.getStructurePositions()); //$NON-NLS-1$
66
			rw.eval("rm(structurenames)"); //$NON-NLS-1$
67
			// if (structurenames != null) structurenames = new
68
			// String[structurepositions.length];
69
			for(int i = 0; i < progression.getStructureNames().length; i++) { // Fix empty attribute values
70
				if("".equals(progression.getStructureNames()[i]) || progression.getStructureNames()[i] == null) {  //$NON-NLS-1$
71
					progression.getStructureNames()[i] = "--"; //$NON-NLS-1$
72
				}
73
			}
74
			rw.addVectorToWorkspace("structurenames", progression.getStructureNames()); //$NON-NLS-1$
75
			// System.out.println("create list positions");
76
			// rw.getConnection().assign("positions",Rpositions);
77

  
78
			// System.out.println("create colors vector");
79
			rw.eval("rm(colors)"); //$NON-NLS-1$
80
			if(grayscale) {
81
				rw.addVectorToWorkspace("colors", Progression2.monocolors); //$NON-NLS-1$
82
			}
83
			else {
84
				if(progression.getQueries().size() <= 5) {
85
					// System.out.println("uses colors5");
86
					rw.addVectorToWorkspace("colors", Progression2.colors5); //$NON-NLS-1$
87
				}
88
				else if(progression.getQueries().size() <= 10) {
89
					// System.out.println("uses colors10");
90
					rw.addVectorToWorkspace("colors", Progression2.colors10); //$NON-NLS-1$
91
				}
92
				else {
93
					// System.out.println("uses colors16");
94
					rw.addVectorToWorkspace("colors", Progression2.colors); //$NON-NLS-1$
95
				}
96
			}
97

  
98
			// System.out.println("create styles vector");
99
			rw.eval("rm(styles)"); //$NON-NLS-1$
100
			if(monostyle) {
101
				rw.addVectorToWorkspace("styles", Progression2.monostyles); //$NON-NLS-1$
102
			}
103
			else {
104
				rw.addVectorToWorkspace("styles", Progression2.styles); //$NON-NLS-1$
105
			}
106

  
107
			// System.out.println("create styles vector");
108
			rw.eval("rm(widths)"); //$NON-NLS-1$
109
			rw.addVectorToWorkspace("widths", Progression2.monowidths); //$NON-NLS-1$
110

  
111
			// System.out.println("create names vector");
112
			String[] queriesstring = new String[progression.getQueries().size()];
113
			for(int i = 0; i < progression.getQueries().size(); i++) {
114
				queriesstring[i] = progression.getQueries().get(i).getQueryString();
115
			}
116
			rw.eval("rm(names)"); //$NON-NLS-1$
117
			rw.addVectorToWorkspace("names", queriesstring); //$NON-NLS-1$
118

  
119
			String name = progression.getCorpus().getName();
120

  
121
			String title = Utils.createProgressionChartTitle(progression, cumulative);
122

  
123
			// Escape title string
124
			title = StringEscapeUtils.escapeJava(title);
125

  
126
			// System.out.println("BANDE="+bande);
127
			String cmd = "progression(positions, names, colors, styles, widths, \"" + name + "\"," + progression.getXminCorpus() + "," + progression.getXmaxCorpus() + ",\"" + cumulative + "\",structurepositions,structurenames, \"" + title + "\", " + progression.getBande() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
128
			rw.plot(file, cmd, ((RChartsEngine) this.chartsEngine).getRDevice());
129

  
130
			RWorkspace.getRWorkspaceInstance().eval(Progression2.prefixR + Progression2.norep + " <- list(positions=positions, names=names, xmin=" + progression.getXminCorpus() + ",xmax=" + progression.getXmaxCorpus() + ", structpositions=structurepositions, structnames=structurenames)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
131
			Progression2.norep++;
132
			Log.info("R exec : " + cmd);
133
		}
134
		catch(RWorkspaceException e) {
135
			// TODO Auto-generated catch block
136
			org.txm.utils.logger.Log.printStackTrace(e);
137
		}
138
		catch(REXPMismatchException e) {
139
			// TODO Auto-generated catch block
140
			org.txm.utils.logger.Log.printStackTrace(e);
141
		}
142
		catch(StatException e) {
143
			// TODO Auto-generated catch block
144
			org.txm.utils.logger.Log.printStackTrace(e);
145
		}
146

  
147
		return file;
148
	}
149

  
150

  
151
	@Override
152
	public Class getResultDataType() {
153
		return Progression2.class;
154
	}
155

  
156

  
157
}
0 158

  
tmp/org.txm.progression.core/src/org/txm/progression/core/chartsengine/base/Utils.java (revision 37)
1
package org.txm.progression.core.chartsengine.base;
2

  
3
import org.txm.chartsengine.core.ChartCreator;
4
import org.txm.progression.core.functions.Progression2;
5
import org.txm.progression.core.messages.TBXProgressionMessages;
6

  
7
/**
8
 * Creates a progression chart from the specified <code>Progression</code> result.
9
 * @author sjacquot
10
 *
11
 */
12
public abstract class Utils extends ChartCreator {
13

  
14
	public Utils() {
15
		// TODO Auto-generated constructor stub
16
	}
17

  
18

  
19
	/**
20
	 * Creates a string title, shared by charts engine implementations, for the progression chart from the specified result.
21
	 * @param the progression result
22
	 * @param doCumulative
23
	 * @return the titles string
24
	 */
25
	public static String createProgressionChartTitle(Progression2 progression, boolean doCumulative)	{
26

  
27
		String title = TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_PROGRESSION_OF + " "; //$NON-NLS-1$
28

  
29
		// Put queries in title
30
		for(int i = 0; i < progression.getQueries().size(); i++) {
31
			title +=  progression.getQueries().get(i).getQueryString();
32
			if(i < progression.getQueries().size() - 1)	{
33
				title += ", "; //$NON-NLS-1$
34
			}
35
		}
36

  
37

  
38
		title += " " + TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_IN + " " + progression.getCorpus().getName(); //$NON-NLS-1$ //$NON-NLS-2$
39

  
40
		if(!doCumulative)	{
41
			title += " " + TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_DENSITY; //$NON-NLS-1$
42
		}
43

  
44

  
45
		// FIXME : is this useful ? I needed to create the setName() method for this.
46
		progression.setName(title);
47

  
48
		if (progression.getStructure() != null) {
49
			title += "\n(" + TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_STRUCT + progression.getStructure().getName();
50
			if (progression.getProperty() != null) {
51
				title += TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_PROPERTY + progression.getProperty().getName();
52
				if (progression.getPropertyRegex() != null)	{
53
					title += TBXProgressionMessages.ChartsEngine_PROGRESSION_TITLE_VALUE + progression.getPropertyRegex();
54
				}
55
			}
56
			title += ")";
57
		}
58

  
59
		return title;
60
	}
61
	
62
}
0 63

  
tmp/org.txm.progression.core/src/org/txm/progression/core/chartsengine/jfreechart/themes/highcharts/renderers/ProgressionItemSelectionRenderer.java (revision 37)
1
package org.txm.progression.core.chartsengine.jfreechart.themes.highcharts.renderers;
2

  
3
import java.awt.Color;
4
import java.awt.Paint;
5
import java.awt.Shape;
6
import java.awt.geom.AffineTransform;
7
import java.util.ArrayList;
8

  
9
import org.jfree.chart.ChartPanel;
10
import org.jfree.chart.labels.XYToolTipGenerator;
11
import org.jfree.data.xy.XYDataset;
12
import org.jfree.data.xy.XYSeriesCollection;
13
import org.txm.chartsengine.core.ChartsEngine;
14
import org.txm.chartsengine.jfreechart.core.renderers.interfaces.IItemSelectionRenderer;
15
import org.txm.chartsengine.jfreechart.core.themes.highcharts.defaulttheme.renderers.ItemSelectionXYStepRenderer;
16
import org.txm.chartsengine.jfreechart.core.themes.highcharts.defaulttheme.swing.CustomHTMLToolTip;
17
import org.txm.progression.core.functions.Progression2;
18
import org.txm.searchengine.cqp.clientExceptions.CqiClientException;
19
import org.txm.searchengine.cqp.corpus.Property;
20
import org.txm.searchengine.cqp.corpus.query.Match;
21

  
22
/**
23
 * Renderer providing item selection system and drawing features for selected item and custom rendering for Progression charts.
24
 * @author sjacquot
25
 *
26
 */
27
public class ProgressionItemSelectionRenderer extends ItemSelectionXYStepRenderer {
28

  
29

  
30
	/**
31
	 * Needed to get the Graphics2D object to use in getItemShape() to compute the label text bounds and draw a background rectangle.
32
	 */
33
	protected ChartPanel chartPanel;
34

  
35
	/**
36
	 * Stack to store selected items to draw at last, over others items.
37
	 */
38
	protected ArrayList itemsToDrawAtLast; 
39
	
40

  
41
	/**
42
	 * Creates a renderer dedicated to CA charts.
43
	 */
44
	public ProgressionItemSelectionRenderer() {
45
		super();
46
		this.setChartType(ChartsEngine.CHART_TYPE_PROGRESSION);
47
		// FIXME: simple selection mode
48
		//((MultipleItemsSelector) this.multipleItemsSelector).setSimpleSelectionMode(true);
49
	}
50

  
51

  
52

  
53
	/**
54
	 * Initializes the tool tip generator.
55
	 */
56
	public void initToolTipGenerator(final IItemSelectionRenderer renderer)	{
57
		this.setBaseToolTipGenerator(new XYToolTipGenerator() {
58

  
59
			@Override
60
			public String generateToolTip(XYDataset dataset, int series, int item) {
61

  
62
				// Hexadecimal color
63
				Color color = (Color) getSeriesPaint(series);
64
				String hex = "#" + Integer.toHexString(color.getRGB()).substring(2);
65
				XYSeriesCollection xyDataset = (XYSeriesCollection) dataset;
66

  
67
//
68
//				// FIXME: test affichage des concordances des occurrences directement dans le tooltip
69
//				// Progression
70
				String concordanceStr = "";
71

  
72
//				if(renderer.getChartType() == ChartsEngine.CHART_TYPE_PROGRESSION)	{
73
//					try {
74
//						Progression progression = ((Progression)renderer.getItemSelector().getResultData());
75
//							//System.out.println("ItemSelectionXYStepRenderer.initToolTipGenerator(...).new XYToolTipGenerator() {...}.generateToolTip() query: " + progression.getQueries().get(xyDataset.getSeriesIndex(xyDataset.getSeries(series).getKey())));
76
//						Property analysisProperty = progression.
77
//								getCorpus().
78
//								getProperty("word");
79
//						List<Property> viewProperties = new ArrayList<Property>();
80
//						viewProperties.add(progression.
81
//								getCorpus().
82
//								getProperty("word"));
83
//						ReferencePattern referencePattern = new ReferencePattern();
84
//						ReferencePattern refAnalysePattern = new ReferencePattern();
85
//						Concordance concordance = new Concordance(progression.getCorpus(), progression.getQueries().get(xyDataset.getSeriesIndex(xyDataset.getSeries(series).getKey())), analysisProperty, viewProperties, referencePattern, refAnalysePattern, 10, 10);
86
//
87
//						System.err.println("ItemSelectionXYStepRenderer.initToolTipGenerator(...).new XYToolTipGenerator() {...}.generateToolTip() concordance nlines: " + concordance.getNLines());
88
//						System.err.println("ItemSelectionXYStepRenderer.initToolTipGenerator(...).new XYToolTipGenerator() {...}.generateToolTip() item position: " + (xyDataset.getSeries(series).getY(item).intValue() - 1));
89
//
90
//
91
//
92
//						Line line = concordance.getLines(xyDataset.getSeries(series).getY(item).intValue() - 1, xyDataset.getSeries(series).getY(item).intValue() - 1).get(0);
93
//						concordanceStr = "<p>" + line.leftContextToString() + " <b>" + line.keywordToString() + "</b> " + line.rightContextToString() + "</p>";
94
//						//xyDataset.getSeriesIndex(xyDataset.getSeries(series).getKey())
95
//					}
96
//					catch(CqiClientException e) {
97
//						// TODO Auto-generated catch block
98
//						e.printStackTrace();
99
//					}
100
//					catch(IOException e) {
101
//						// TODO Auto-generated catch block
102
//						e.printStackTrace();
103
//					}
104
//					catch(CqiServerError e) {
105
//						// TODO Auto-generated catch block
106
//						e.printStackTrace();
107
//					}
108
//				}
109

  
110
				String token = xyDataset.getSeriesKey(series).toString();
111
				token = token.substring(0, token.lastIndexOf(" "));
112
				int tokenCount = xyDataset.getSeries(series).getItemCount() - 2; // -2 for the 0 point and the dummy last point
113

  
114
				return CustomHTMLToolTip.getDefaultHTMLBody(renderer, hex) + "<p><span style=\"color: " + hex + ";\">" + token + "</span> <b>(" + valuesNumberFormat.format(xyDataset.getSeries(series).getY(item)) + " / " + tokenCount + ")</b>"
115
						+ "</p></body><html>";
116
				
117
				// FIXME: test contexts in tool tip
118
//				return CustomHTMLToolTip.getDefaultHTMLBody(renderer, hex) + "<p><span style=\"color: " + hex + ";\">" + xyDataset.getSeriesKey(series)
119
//						+ "</span></p><p><b>" + valuesNumberFormat.format(xyDataset.getSeries(series).getY(item)) + ChartsEngineMessages.ChartsEngine_LABEL_VALUE_SEPARATORS
120
//						+ " </b><b>" + valuesNumberFormat.format(xyDataset.getSeries(series).getX(item)) + "</b>"
121
//						+ concordanceStr
122
//						+ "</p></body><html>";
123
				
124
			}
125
		});
126
	}
127
	
128
	
129
	
130
	@Override
131
	public Paint getItemPaint(int series, int item) {
132

  
133
		Color color = (Color) super.getItemPaint(series, item);
134

  
135
		// Skip the line pass
136
		if(!isLinePass)	{
137

  
138
			// Change selected item shape color, reducing transparency
139
			if(this.multipleItemsSelector.isMouseOverItem(series, item)) {
140
				return new Color(color.getRed(), color.getGreen(), color.getBlue(), 195);
141
			}
142
			// Multiple item selection
143
//			else if(this.itemSelector.isMultipleSelectedItem(series, item))	{
144
//				// FIXME: rendering tests
145
//				return new Color(130, 130, 130, 195);
146
//				//return new Color(color.getRed(), color.getGreen(), color.getBlue(), 140);
147
//			}
148

  
149
		}
150
		
151
		return color;
152
	}
153

  
154

  
155
	@Override
156
	public Shape getItemShape(int series, int item) {
157

  
158
		Shape s = super.getItemShape(series, item);
159
		AffineTransform t = new AffineTransform();
160
		// If not selected item reduce the shape therefore it will be hidden by the lines chart
161
		if(!this.multipleItemsSelector.isMouseOverItem(series, item) && !this.multipleItemsSelector.isSelectedItem(series, item)) {
162
			t.setToScale(0.1, 0.1);
163
		}
164
		// FIXME: Multiple selection
165
//		else if(this.itemSelector.isMultipleSelectedItem(series, item))	{
166
////			
167
//			// Add a background rectangle to the label selected item
168
//			XYSeriesCollection dataset = (XYSeriesCollection) this.getPlot().getDataset();
169
//					
170
//			Graphics2D graphics = ((Graphics2D) this.chartPanel.getGraphics());
171
//			 
172
//			// FIXME: get graphics by creating an image insetad of passing the chart panel to this renderer
173
////			BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
174
////			Graphics2D graphics = img.createGraphics();
175
//			// FIXME: rendering quality tests
176
////			RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
177
////			rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
178
////			rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
179
////			rh.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
180
////		    graphics.setRenderingHints(rh);
181
//			
182
//			Font font = this.getItemLabelFont(series, item);
183
//			String label = valuesNumberFormat.format(dataset.getSeries(series).getY(item)) + " / " + (dataset.getSeries(series).getItemCount() - 2); //$NON-NLS-1$ // -2 for the 0 point and the dummy last point;
184
//
185
//			GlyphVector v = font.createGlyphVector(graphics.getFontMetrics(font).getFontRenderContext(), label);
186
//	        Shape labelShape = v.getOutline();
187
//	        //Rectangle2D labelBounds = v.getVisualBounds();
188
//	        
189
//			Rectangle2D labelBounds = font.getStringBounds(label, graphics.getFontRenderContext());
190
//
191
//			// FIXME : not rounded rectangle version
192
////			Shape labelBackground = new Rectangle2D.Double(-bounds.getWidth() / 2, -s.getBounds2D().getHeight() / 2 + 1, bounds.getWidth() + 4, bounds.getHeight() / 2 + 8);
193
//
194
//			//Rectangle2D labelBounds = font.getStringBounds(label, graphics.getFontRenderContext());
195
//			
196
//	        //Rectangle labelBounds = labelShape.getBounds();
197
//	        
198
//			//Shape labelBackground = new RoundRectangle2D.Double(-(labelBounds.getWidth() + 4) / 2, -s.getBounds2D().getHeight() / 2 + 1, labelBounds.getWidth() + 8, labelBounds.getHeight() / 2 + 10, 5, 5);
199
//			double width = labelBounds.getWidth() + 10;
200
//			double height = labelBounds.getHeight() + 10;
201
//			Shape labelBackground = new RoundRectangle2D.Double(-width  / 2, -height / 2 - 15, width, height, 5, 5);
202
//			
203
//			AffineTransform t2 = new AffineTransform();
204
//			t2.setToScale(0.9, 0.9);
205
//			Shape labelBackground2 = t2.createTransformedShape(labelBackground);
206
//			
207
//			
208
//			Area a = new Area(s);
209
//			a.add(new Area(labelBackground));
210
//			//a.add(new Area(labelBackground2));
211
//			//a.add(new Area(labelShape));
212
//			
213
//			s = a;
214
//			//t.setToScale(1.5, 1.5);
215
//
216
//			//return a;
217
//			
218
//		}
219
		else	{
220
			t.setToScale(1.5, 1.5);
221
		}
222
		s = t.createTransformedShape(s);
223
		return s;
224
	}
225

  
226

  
227
	/**
228
	 * @param chartPanel the chartPanel to set
229
	 */
230
	public void setChartPanel(ChartPanel chartPanel) {
231
		this.chartPanel = chartPanel;
232
	}
233

  
234
	
235
	@Override
236
	public String getSelectedItemLabelFromDataset(XYDataset dataset, int series, int item)	{
237
		
238
		// manage the first and last dummy point
239
		if(item == 0)	{
240
			item++;
241
		}
242
		else if(item == dataset.getItemCount(series) - 1)	{
243
			item--;
244
		}
245
		
246
		String label = "";
247
		int globalPosition = (int) dataset.getXValue(series, item) + 1;
248
		
249
		try {
250
			
251
			Property prop;
252
			
253
			// Ref
254
			prop = ((Progression2)this.multipleItemsSelector.getResultData()).getCorpus().getProperty("ref"); //$NON-NLS-1$
255
			// Text id
256
			if(prop == null)	{
257
				prop = ((Progression2)this.multipleItemsSelector.getResultData()).getCorpus().getStructuralUnit("text").getProperty("id"); //$NON-NLS-1$ //$NON-NLS-2$
258
			}
259
			
260
			Match selectedWordMatch = new Match(globalPosition, globalPosition);
261
			label = selectedWordMatch.getValueForProperty(prop);
262
			
263
		}
264
		catch(CqiClientException e) {
265
			// TODO Auto-generated catch block
266
			e.printStackTrace();
267
		}
268
		
269
		// manage the first 0 dummy point
270
		if(item == 0)	{
271
			item++;
272
		}
273
		
274
		int tokenCount = ((XYSeriesCollection)dataset).getSeries(series).getItemCount() - 2; // -2 for the 0 point and the dummy last point
275
		label += "\n" + globalPosition + " / " + valuesNumberFormat.format(((XYSeriesCollection)dataset).getDomainUpperBound(false)); //$NON-NLS-1$ //$NON-NLS-2$ // -2 for the 0 point and the dummy last point
276

  
277
		label += "\n" + valuesNumberFormat.format(((XYSeriesCollection) dataset).getSeries(series).getY(item)) + " / " + (((XYSeriesCollection) dataset).getSeries(series).getItemCount() - 2); //$NON-NLS-1$ //$NON-NLS-2$ // -2 for the 0 point and the dummy last point 
278
		
279
		return label;
280
	}
281
	
282

  
283

  
284
}
0 285

  
tmp/org.txm.progression.core/src/org/txm/progression/core/chartsengine/jfreechart/themes/highcharts/JFCProgressionChartCreator.java (revision 37)
1
package org.txm.progression.core.chartsengine.jfreechart.themes.highcharts;
2

  
3
import java.awt.BasicStroke;
4
import java.awt.Color;
5
import java.util.List;
6

  
7
import org.jfree.chart.JFreeChart;
8
import org.jfree.chart.axis.NumberAxis;
9
import org.jfree.chart.plot.Marker;
10
import org.jfree.chart.plot.ValueMarker;
11
import org.jfree.data.xy.XYSeries;
12
import org.jfree.data.xy.XYSeriesCollection;
13
import org.jfree.ui.RectangleAnchor;
14
import org.jfree.ui.TextAnchor;
15
import org.txm.chartsengine.core.ChartsEngine;
16
import org.txm.chartsengine.core.preferences.ChartsEnginePreferences;
17
import org.txm.chartsengine.jfreechart.core.JFCChartCreator;
18
import org.txm.chartsengine.jfreechart.core.renderers.interfaces.IItemSelectionRenderer;
19
import org.txm.chartsengine.jfreechart.core.themes.base.ExtendedNumberAxis;
20
import org.txm.progression.core.chartsengine.base.Utils;
21
import org.txm.progression.core.chartsengine.jfreechart.themes.highcharts.renderers.ProgressionItemSelectionRenderer;
22
import org.txm.progression.core.functions.Progression2;
23
import org.txm.progression.core.messages.TBXProgressionMessages;
24
import org.txm.progression.core.preferences.ProgressionPreferences;
25
import org.txm.searchengine.cqp.corpus.query.Query;
26
import org.txm.tbx.preferences.TXMPreferences;
27

  
28
/**
29
 * JFC progression chart creator.
30
 * 
31
 * @author sjacquot
32
 *
33
 */
34
public class JFCProgressionChartCreator extends JFCChartCreator {
35

  
36
	public JFCProgressionChartCreator() {
37
		// TODO Auto-generated constructor stub
38
	}
39

  
40
	@Override
41
	public JFreeChart createChart(Object resultData, String preferencesNode) {
42

  
43
		
44
		Progression2 progression = (Progression2) resultData;
45
		
46
		// parameters
47
//		boolean grayscale = (Boolean)params[0];
48
//		boolean monostyle = (Boolean)params[1];
49
//		boolean cumulative = (Boolean)params[2];
50

  
51
		boolean grayscale = TXMPreferences.getBoolean(preferencesNode, resultData, ProgressionPreferences.MONOCHROMATIC);
52
		boolean monostyle = TXMPreferences.getBoolean(preferencesNode, resultData, ProgressionPreferences.MONO_STYLE);
53
		boolean cumulative = TXMPreferences.getBoolean(preferencesNode, resultData, ProgressionPreferences.CUMULATIVE);
54
		
55
		
56
		JFreeChart chart = null;
57

  
58
		// Create the dataset
59
		XYSeriesCollection dataset = new XYSeriesCollection();
60
		List<int[]> positions = progression.getAllpositions();
61
		List<Query> queries = progression.getQueries();
62
		// Y axis label
63
		String yAxisLabel;
64

  
65
		// Cumulative
66
		if(cumulative)	{
67
			for(int i = 0; i < progression.getAllpositions().size(); i++) {
68
				int[] list = positions.get(i);
69
				Query query = queries.get(i);
70
				XYSeries series = new XYSeries(query.toString() + " " + list.length);
71
				int c = 1;
72
				for(int j = 0; j < list.length; j++) {
73
					// Add a first point to draw a vertical line
74
					if(j == 0)	{
75
						series.add(list[j], 0);
76
					}
77
					series.add(list[j], c++);
78
				}
79

  
80
				// FIXME: add a dummy point to draw horizontal line between last point and max X corpus
81
				series.add(progression.getXmaxCorpus(), --c);
82
				dataset.addSeries(series);
83
			}
84

  
85
			// Create the chart
86
			yAxisLabel = TBXProgressionMessages.ChartsEngine_PROGRESSION_Y_AXIS_CUMULATIVE_LABEL;
87
			chart = this.getChartsEngine().createXYStepChart(dataset, Utils.createProgressionChartTitle(progression, cumulative),
88
					TBXProgressionMessages.bind(TBXProgressionMessages.ChartsEngine_PROGRESSION_X_AXIS_LABEL, progression.getXmaxCorpus()), yAxisLabel, true, true, true, true, true);
89

  
90

  
91
			// Custom renderer
92
			chart.getXYPlot().setRenderer(new ProgressionItemSelectionRenderer());
93

  
94
		}
95
		// FIXME : Density, to implement when textometry R package will store the result in the Progression class
96
		else	{
97

  
98
			// FIXME : density not yet implemented
99
			System.err.println("JFCChartsEngine.createProgressionChart(): density mode not yet implemented.");
100

  
101
			for(int i = 0; i < progression.getAllpositions().size(); i++) {
102
				int[] liste = positions.get(i);
103
				Query query = queries.get(i);
104
				XYSeries series = new XYSeries(query.toString() + " " + liste.length);
105

  
106
				for(int j = 0; j <  liste.length; j++) {
107

  
108
					// FIXME : tests y
109
					// y <- c( c(0), y , c(y[[length(x)]]) ) // R code
110
					// FIXME : random Y value
111
					double y = progression.getAllpositions().get(i)[j] * Math.random();
112
	//				double y = progression.getAllpositions().get(i)[j];
113
					series.add(liste[j], y);
114
				}
115
				dataset.addSeries(series);
116
			}
117

  
118
			// Create the chart
119
			yAxisLabel =  TBXProgressionMessages.ChartsEngine_PROGRESSION_Y_AXIS_NOT_CUMULATIVE_LABEL;
120
			chart = this.getChartsEngine().createXYLineChart(dataset, Utils.createProgressionChartTitle(progression, cumulative),
121
					TBXProgressionMessages.bind(TBXProgressionMessages.ChartsEngine_PROGRESSION_X_AXIS_LABEL, progression.getXmaxCorpus()), yAxisLabel,
122
					true, true, true, false, true, false, true, null);
123
		}
124

  
125

  
126

  
127
        ((IItemSelectionRenderer) chart.getXYPlot().getRenderer()).setChartType(ChartsEngine.CHART_TYPE_PROGRESSION);
128
        ((IItemSelectionRenderer) chart.getXYPlot().getRenderer()).getItemsSelector().setResultData(progression);
129

  
130

  
131
		// Add the limit markers
132
		BasicStroke dashedStroke = new BasicStroke(0.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {2f}, 0f);
133
		Marker marker = new ValueMarker(progression.getXminCorpus());
134
        marker.setPaint(Color.gray);
135
        marker.setStroke(dashedStroke);
136
        chart.getXYPlot().addDomainMarker(marker);
137
		marker = new ValueMarker(progression.getXmaxCorpus());
138
        marker.setPaint(Color.gray);
139
        marker.setStroke(dashedStroke);
140
        chart.getXYPlot().addDomainMarker(marker);
141

  
142

  
143
//        // FIXME : limit with annotations rather than markers (marker height is dynamically adapted to the real chart height.
144
        // Annotation have a fixed height)
145
//        XYLineAnnotation annotation = new XYLineAnnotation(0, 0, 0, dataset.getRangeUpperBound(true), dashedStroke, Color.gray);
146
//        chart.getXYPlot().addAnnotation(annotation, true);
147

  
148
		// Add the part markers
149
		if(progression.getStructurePositions().length > 0)	{
150
			for(int i = 0; i < progression.getStructurePositions().length; i++) {
151
				if(progression.getStructurePositions()[i] != 0)	{
152
					marker = new ValueMarker(progression.getStructurePositions()[i]);
153
			        marker.setPaint(Color.black);
154
			        marker.setLabel(progression.getStructureNames()[i]);
155
			        marker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
156
			        marker.setLabelTextAnchor(TextAnchor.HALF_ASCENT_LEFT);
157

  
158

  
159
			        // FIXME: test of rotated annotations rather than using marker label. The problem with this is that the position of annotation is not adjusted when zooming/dezooming.
160
			        // FIXME: the best approach is to redefine the drawing method of
161
////			        double start = marker.getStartValue();
162
////			        double end = TempIntervalMarker.getEndValue();
163
////			        double middle = (end - start)/2;
164
//			        XYTextAnnotation updateLabel = new XYTextAnnotation("Update", progression.getStructurePositions()[i], 0);
165
//			        updateLabel.setFont(new Font("Sans Serif", Font.BOLD, 10));
166
//			        updateLabel.setRotationAnchor(TextAnchor.BASELINE_CENTER);
167
//			        updateLabel.setTextAnchor(TextAnchor.BASELINE_CENTER);
168
//			        updateLabel.setRotationAngle(3.14 / 2);
169
//			        updateLabel.setPaint(Color.black);
170
//			        chart.getXYPlot().addAnnotation(updateLabel);
171

  
172

  
173

  
174
			        chart.getXYPlot().addDomainMarker(marker);
175
				}
176
			}
177
		}
178

  
179
		// Custom domain axis for ticks drawing options
180
		chart.getXYPlot().setDomainAxis(new ExtendedNumberAxis((NumberAxis) chart.getXYPlot().getDomainAxis(), true, true, progression.getXminCorpus(), progression.getXmaxCorpus()));
181

  
182
		// Custom range axis for ticks drawing options
183
		chart.getXYPlot().setRangeAxis(new ExtendedNumberAxis((NumberAxis) chart.getXYPlot().getRangeAxis(), false, true, 0, progression.getMaxY()));
184

  
185
		// Match the X-axis origin value to the min x corpus (for subcorpus case)
186
		chart.getXYPlot().getDomainAxis().setLowerBound(progression.getXminCorpus());
187

  
188

  
189
//        int itemsColorsRenderingMode = Theme.ITEMS_RENDERING_COLORS_MODE;
190
//		// Grayscale
191
//        if(grayscale)	{
192
//        	itemsColorsRenderingMode = Theme.ITEMS_RENDERING_GRAYSCALE_MODE;
193
//        }
194

  
195
        // Re-apply theme to the chart to match the colors rendering mode
196
        // FIXME : the rendering mode should be pass to all methods, even base methods as createXYLineChart(), createBarChart(), etc.
197
        // or better, to be stocked into a member variable in the theme ?
198
      //  this.getChartsEngine().getTheme().applyThemeToChart(chart, TXMPreferences.getInt(ProgressionPreferences.PREFERENCES_NODE, resultData, ChartsEnginePreferences.RENDERING_COLORS_MODE, ChartsEnginePreferences.PREFERENCES_NODE), monostyle);
199

  
200
		// synchronizes the chart with the shared preferences 
201
		//super.syncChart(chart, resultData, ProgressionPreferences.PREFERENCES_NODE);
202
		
203
		return chart;
204
		
205
	}
206

  
207

  
208
	@Override
209
	public Class getResultDataType() {
210
		return Progression2.class;
211
	}
212

  
213

  
214
	
215

  
216
}
0 217

  
tmp/org.txm.progression.core/src/org/txm/progression/core/package.html (revision 37)
1
<html>
2
<body>
3
<p>Progression - inspired by Weblex.</p>
4
</body>
5
</html>
0 6

  
tmp/org.txm.progression.core/src/org/txm/progression/core/preferences/ProgressionPreferences.java (revision 37)
1
package org.txm.progression.core.preferences;
2

  
3

  
4
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
5
import org.eclipse.core.runtime.preferences.DefaultScope;
6
import org.osgi.framework.FrameworkUtil;
7
import org.osgi.service.prefs.Preferences;
8

  
9
/**
10
 * Default preferences initializer.
11
 * 
12
 * @author mdecorde
13
 * @author sjacquot
14
 *
15
 */
16
public class ProgressionPreferences extends AbstractPreferenceInitializer {
17

  
18

  
19
	// auto populate the preference node qualifier from the current bundle id
20
	public static final String PREFERENCES_NODE = FrameworkUtil.getBundle(ProgressionPreferences.class).getSymbolicName();
21

  
22
	
23
	public static final String PREFERENCES_PREFIX = "progression_"; //$NON-NLS-1$
24
	
25
	/** The Constant MONOCHROMATIC. */
26
	public static final String MONOCHROMATIC = PREFERENCES_PREFIX + "monochrome"; //$NON-NLS-1$
27
	
28
	/** The Constant CUMULATIVE. */
29
	public static final String CUMULATIVE = PREFERENCES_PREFIX + "cumulative"; //$NON-NLS-1$
30
	
31
	/** The Constant REPEAT_VALUES. */
32
	public static final String REPEAT_VALUES = PREFERENCES_PREFIX + "repeat_values"; //$NON-NLS-1$
33
	
34
	/** The Constant BANDE_MULTIPLIER. */
35
	public static final String BANDE_MULTIPLIER = PREFERENCES_PREFIX + "bande_multiplier"; //$NON-NLS-1$
36
	
37
	/** The Constant MONO_STYLE. */
38
	public static final String MONO_STYLE = PREFERENCES_PREFIX + "_mono_style"; //$NON-NLS-1$
39
	
... Ce différentiel a été tronqué car il excède la taille maximale pouvant être affichée.

Formats disponibles : Unified diff