Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / rendering / AbstractIntervalLegend.java @ 18621

History | View | Annotate | Download (16.8 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41

    
42
/* CVS MESSAGES:
43
*
44
* $Id: AbstractIntervalLegend.java 18621 2008-02-08 07:59:54Z jdominguez $
45
* $Log$
46
* Revision 1.12  2007-09-19 16:25:39  jaume
47
* ReadExpansionFileException removed from this context and removed unnecessary imports
48
*
49
* Revision 1.11  2007/09/10 15:47:11  jaume
50
* *** empty log message ***
51
*
52
* Revision 1.10  2007/08/03 09:22:08  jaume
53
* refactored class names
54
*
55
* Revision 1.9  2007/08/02 10:19:03  jvidal
56
* implements IPersistance
57
*
58
* Revision 1.8  2007/08/01 11:45:59  jaume
59
* passing general tests (drawing test yet missing)
60
*
61
* Revision 1.7  2007/05/28 15:36:42  jaume
62
* *** empty log message ***
63
*
64
* Revision 1.6  2007/05/17 09:32:06  jaume
65
* *** empty log message ***
66
*
67
* Revision 1.5  2007/05/10 14:13:36  jaume
68
* *** empty log message ***
69
*
70
* Revision 1.4  2007/05/10 09:44:08  jaume
71
* Refactored legend interface names
72
*
73
* Revision 1.3  2007/03/27 09:28:40  jaume
74
* *** empty log message ***
75
*
76
* Revision 1.2  2007/03/09 11:20:56  jaume
77
* Advanced symbology (start committing)
78
*
79
* Revision 1.1.2.2  2007/02/15 16:23:44  jaume
80
* *** empty log message ***
81
*
82
* Revision 1.1.2.1  2007/02/13 16:19:19  jaume
83
* graduated symbol legends (start commiting)
84
*
85
*
86
*/
87
package com.iver.cit.gvsig.fmap.rendering;
88

    
89
import java.util.ArrayList;
90
import java.util.Comparator;
91
import java.util.Iterator;
92
import java.util.TreeMap;
93

    
94
import org.apache.log4j.Logger;
95

    
96
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
97
import com.hardcode.gdbms.engine.data.DataSource;
98
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
99
import com.hardcode.gdbms.engine.values.DateValue;
100
import com.hardcode.gdbms.engine.values.DoubleValue;
101
import com.hardcode.gdbms.engine.values.FloatValue;
102
import com.hardcode.gdbms.engine.values.IntValue;
103
import com.hardcode.gdbms.engine.values.LongValue;
104
import com.hardcode.gdbms.engine.values.NullValue;
105
import com.hardcode.gdbms.engine.values.Value;
106
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
107
import com.iver.cit.gvsig.fmap.Messages;
108
import com.iver.cit.gvsig.fmap.core.IFeature;
109
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
110
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
111
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
112

    
113
public abstract class AbstractIntervalLegend extends AbstractClassifiedVectorLegend implements IVectorialIntervalLegend{
114
        protected int shapeType;
115

    
116
        public static final int EQUAL_INTERVALS = 0;
117
        public static final int NATURAL_INTERVALS = 1;
118
        public static final int QUANTILE_INTERVALS = 2;
119
        protected TreeMap<Object, ISymbol> symbols = new TreeMap<Object, ISymbol>
120
                        (new Comparator<Object>() {
121
                public int compare(Object o1, Object o2) {
122
                        if ((o1 != null) && (o2 != null)) {
123
                                if (o1 instanceof NullIntervalValue &&
124
                                                o2 instanceof NullIntervalValue) {
125
                                        return 0;
126
                                }
127

    
128
                                if (o2 instanceof NullIntervalValue) {
129
                                        return 1;
130
                                }
131

    
132
                                if (o1 instanceof NullIntervalValue) {
133
                                        return -1;
134
                                }
135

    
136
                                FInterval i2 = (FInterval) o2;
137
                                FInterval i1 = (FInterval) o1;
138

    
139
                                if (i1.getMin() > i2.getMin()) {
140
                                        return 1;
141
                                }
142

    
143
                                if (i1.getMin() < i2.getMin()) {
144
                                        return -1;
145
                                }
146
                                if (i1.getMax() < i2.getMax()) {
147
                                        return -1;
148
                                }
149
                                if (i1.getMax() > i2.getMax()) {
150
                                        return 1;
151
                                }
152
                        }
153

    
154
                        return 0;
155
                }
156
        });
157
        protected ArrayList<Object> keys = new ArrayList<Object>();
158
        protected int index = 0;
159
        protected String[] fieldNames;
160
        protected int fieldId;
161
        protected ISymbol defaultSymbol;
162
        protected DataSource dataSource;
163
        protected int intervalType = NATURAL_INTERVALS;
164
        protected boolean useDefaultSymbol = false;
165

    
166
        private Logger logger = Logger.getLogger(AbstractIntervalLegend.class);
167

    
168
        public void addSymbol(Object key, ISymbol symbol) {
169
                symbols.put(key, symbol);
170
                keys.add(key);
171
        }
172

    
173
        /*
174
         * @see com.iver.cit.gvsig.fmap.rendering.IVectorialLegend#getSymbol(int)
175
         */
176
        public ISymbol getSymbol(int recordIndex) throws ReadDriverException {
177
                Value val = dataSource.getFieldValue(recordIndex, fieldId);
178
                IInterval interval = getInterval(val);
179
                ISymbol theSymbol = getSymbolByInterval(interval);
180

    
181

    
182

    
183
//
184
//                if (shapeType == FShape.POLYGON && theSymbol instanceof IMarkerSymbol) {
185
//                        // transform it to a fill symbol
186
//                        MarkerFillSymbol aux = new MarkerFillSymbol();
187
//                        // tell the fill style to draw the IMarkerSymbol
188
//                        // as a IFillSymbol centering it in the shape polygon
189
//                        // centroid and applying offset (if any).
190
//                        aux.setMarker((IMarkerSymbol) theSymbol);
191
//                        SimpleMarkerFillPropertiesStyle p = new SimpleMarkerFillPropertiesStyle();
192
//                        p.setFillStyle(SimpleMarkerFillPropertiesStyle.SINGLE_CENTERED_SYMBOL);
193
//                        aux.setMarkerFillProperties(p);
194
//                        theSymbol = aux;
195
//                }
196

    
197
                if (theSymbol != null) {
198
                        return theSymbol;
199
                } else if (useDefaultSymbol) {
200
                        return getDefaultSymbol();
201
                }
202

    
203
                return null;
204
        }
205

    
206

    
207
        public ISymbol getSymbolByFeature(IFeature feat) {
208
                Value val = feat.getAttribute(FLyrVect.forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD
209
                        ? 0 :fieldId);
210
                IInterval interval = getInterval(val);
211
                ISymbol theSymbol = getSymbolByInterval(interval);
212

    
213
                if (theSymbol == null) 
214
                        return getDefaultSymbol();
215
//                
216
//                if (shapeType == FShape.POLYGON && theSymbol instanceof IMarkerSymbol) {
217
//                        // transform it to a fill symbol
218
//                        MarkerFillSymbol aux = new MarkerFillSymbol();
219
//                        // tell the fill style to draw the IMarkerSymbol
220
//                        // as a IFillSymbol centering it in the shape polygon
221
//                        // centroid and applying offset (if any).
222
//                        aux.setMarker((IMarkerSymbol) theSymbol);
223
//                        SimpleMarkerFillPropertiesStyle p = new SimpleMarkerFillPropertiesStyle();
224
//                        p.setFillStyle(SimpleMarkerFillPropertiesStyle.SINGLE_CENTERED_SYMBOL);
225
//                        aux.setMarkerFillProperties(p);
226
//                        theSymbol = aux;
227
//                }
228
//                
229
                
230
                return theSymbol;
231
        }
232
        
233
        
234
        public FInterval[] calculateIntervals(DataSource recordSet, String fieldName, int numIntervalos, int shapeType)
235
        throws ReadDriverException, LegendLayerException {
236
                logger.debug("elRs.start()");
237
                recordSet.start();
238

    
239
                int idField = -1;
240
                
241
                setClassifyingFieldNames(new String[] {fieldName});
242

    
243
                String[] fieldNames = getClassifyingFieldNames();
244

    
245

    
246
                for (int i = 0; i < recordSet.getFieldCount(); i++) {
247
                        String nomAux = recordSet.getFieldName(i).trim();
248

    
249
                        if (fieldNames[0].compareToIgnoreCase(nomAux) == 0) {
250
                                idField = i;
251

    
252
                                break;
253
                        }
254
                }
255

    
256
                if (idField == -1) {
257
                        logger.error("Campo no reconocido " + fieldNames);
258

    
259
                        return null;
260
                }
261

    
262
                double minValue = Double.MAX_VALUE;
263
                double maxValue = Double.NEGATIVE_INFINITY;
264

    
265
                VectorialIntervalLegend auxLegend = LegendFactory.
266
                    createVectorialIntervalLegend(shapeType);
267

    
268
                Value clave;
269

    
270
                for (int j = 0; j < recordSet.getRowCount(); j++) {
271
                        clave = recordSet.getFieldValue(j, idField);
272

    
273
                        IInterval interval = auxLegend.getInterval(clave);
274

    
275
                        ////Comprobar que no esta repetido y no hace falta introducir en el hashtable el campo junto con el simbolo.
276
                        if (auxLegend.getSymbolByInterval(interval) == null) {
277
                                //si no esta creado el simbolo se crea
278
                                double valor = 0;
279

    
280

    
281
                                if (clave instanceof IntValue) {
282
                                        valor = ((IntValue) clave).getValue();
283
                                } else if (clave instanceof DoubleValue) {
284
                                        valor = ((DoubleValue) clave).getValue();
285
                                } else if (clave instanceof FloatValue) {
286
                                        valor = ((FloatValue) clave).getValue();
287
                                } else if (clave instanceof LongValue) {
288
                                        valor = ((LongValue) clave).getValue();
289
                                } else if (clave instanceof DateValue) {
290
                                        //TODO POR IMPLEMENTAR
291
                                        ///valorDate = elRs.getFieldValueAsDate(idField);
292
                                        ///if (valorDate.before(minValueDate)) minValueDate = valorDate;
293
                                        ///if (valorDate.after(maxValueDate)) maxValueDate = valorDate;
294
                                } else if (clave instanceof NullValue) {
295
                                        continue;
296
                                }
297

    
298
                                if (valor < minValue) {
299
                                        minValue = valor;
300
                                }
301

    
302
                                if (valor > maxValue) {
303
                                        maxValue = valor;
304
                                }
305
                        }
306
                }
307

    
308
                FInterval[] intervalArray = null;
309
                switch (getIntervalType()) {
310
                case VectorialIntervalLegend.EQUAL_INTERVALS:
311
                        intervalArray = calculateEqualIntervals(numIntervalos,
312
                                        minValue, maxValue, fieldName);
313

    
314
                        break;
315

    
316
                case VectorialIntervalLegend.NATURAL_INTERVALS:
317
                        intervalArray = calculateNaturalIntervals(recordSet, numIntervalos,
318
                                        minValue, maxValue, fieldName);
319

    
320
                        break;
321

    
322
                case VectorialIntervalLegend.QUANTILE_INTERVALS:
323
                        intervalArray = calculateQuantileIntervals(recordSet, numIntervalos,
324
                                        minValue, maxValue, fieldName);
325

    
326
                        break;
327
                }
328
                recordSet.stop();
329
                return intervalArray;
330
        }
331

    
332
        
333
    /**
334
     * EQUAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
335
     * quieren crear. Los intervalos se crean con un tama?o igual entre ellos.
336
     * @param numIntervals n?mero de intervalos
337
     * @param minValue Valor m?nimo.
338
     * @param maxValue Valor m?ximo.
339
     * @param fieldName Nombre del campo
340
     *
341
     * @return Array con los intervalos.
342
     */
343
    private FInterval[] calculateEqualIntervals(int numIntervals, double minValue,
344
        double maxValue, String fieldName) {
345
        FInterval[] theIntervalArray = new FInterval[numIntervals];
346
        double step = (maxValue - minValue) / numIntervals;
347

    
348
        if (numIntervals > 1) {
349
            theIntervalArray[0] = new FInterval(minValue, minValue + step);
350

    
351
            for (int i = 1; i < (numIntervals - 1); i++) {
352
                theIntervalArray[i] = new FInterval(minValue + (i * step) +
353
                        0.01, minValue + ((i + 1) * step));
354
            }
355

    
356
            theIntervalArray[numIntervals - 1] = new FInterval(minValue +
357
                    ((numIntervals - 1) * step) + 0.01, maxValue);
358
        } else {
359
            theIntervalArray[0] = new FInterval(minValue, maxValue);
360
        }
361

    
362
        return theIntervalArray;
363
    }
364

    
365
    /**
366
     * NATURAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
367
     * quieren crear. Los intervalos se distribuyen de forma natural.
368
     *
369
     * @param numIntervals n?mero de intervalos
370
     * @param minValue Valor m?nimo.
371
     * @param maxValue Valor m?ximo.
372
     * @param fieldName Nombre del campo
373
     *
374
     * @return Array con los intervalos.
375
     * @throws LegendLayerException 
376
     */
377
    private FInterval[] calculateNaturalIntervals(DataSource recordSet, int numIntervals, double minValue,
378
        double maxValue, String fieldName) throws LegendLayerException {
379
        NaturalIntervalGenerator intervalGenerator = new NaturalIntervalGenerator(
380
                        recordSet, fieldName, numIntervals);
381

    
382
        try {
383
            intervalGenerator.generarIntervalos();
384
        } catch (ReadDriverException e) {
385
                throw new LegendLayerException(Messages.getString("failed_calculating_intervals"), e);
386
        }
387

    
388
        int numIntervalsGen = intervalGenerator.getNumIntervals() - 1;
389

    
390
        if (numIntervalsGen == -1) {
391
            //TODO cuando no puede calcular los intervalos.
392
            numIntervalsGen = 1;
393
        }
394

    
395
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
396

    
397
        if (numIntervalsGen > 1) {
398
            theIntervalArray[0] = new FInterval(minValue,
399
                    intervalGenerator.getValorRuptura(0));
400

    
401
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
402
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
403
                            1), intervalGenerator.getValorRuptura(i));
404
            }
405

    
406
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
407
                        2), maxValue);
408
        } else {
409
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
410
                    maxValue);
411
        }
412

    
413
        return theIntervalArray;
414
    }
415

    
416
    /**
417
     * QUANTILE INTERVAL Devuelve un Array con el n?mero de intervalos que se
418
     * quieren crear. Los intervalos se distribuyen de forma quantile.
419
     * @param recordSet 
420
     *
421
     * @param numIntervals n?mero de intervalos
422
     * @param minValue Valor m?nimo.
423
     * @param maxValue Valor m?ximo.
424
     * @param fieldName Nombre del campo
425
     *
426
     * @return Array con los intervalos.
427
     * @throws LegendLayerException 
428
     */
429
    private FInterval[] calculateQuantileIntervals(DataSource recordSet, int numIntervals, double minValue,
430
        double maxValue, String fieldName) throws LegendLayerException {
431
        QuantileIntervalGenerator intervalGenerator = new QuantileIntervalGenerator(
432
                        recordSet, fieldName, numIntervals);
433

    
434
        try {
435
            intervalGenerator.generarIntervalos();
436
        } catch (ReadDriverException e) {
437
                throw new LegendLayerException(Messages.getString("failed_calculating_intervals"), e);
438
        }
439

    
440
        int numIntervalsGen = intervalGenerator.getNumIntervalGen();
441
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
442

    
443
        if (intervalGenerator.getNumIntervalGen() > 1) {
444
            theIntervalArray[0] = new FInterval(minValue,
445
                    intervalGenerator.getValRuptura(0));
446

    
447
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
448
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
449
                            1), intervalGenerator.getValRuptura(i));
450
            }
451

    
452
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
453
                        2), maxValue);
454
        } else {
455
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
456
                    maxValue);
457
        }
458

    
459
        return theIntervalArray;
460
    }
461

    
462
        public ISymbol getSymbolByInterval(IInterval key) {
463
                if (key == null) {
464
                        return null;
465
                }
466

    
467
                if (symbols.containsKey(key)) {
468
                        return (ISymbol) symbols.get(key);
469
                }
470

    
471
                return null;
472
        }
473

    
474
        public String[] getDescriptions() {
475
                String[] descriptions = new String[symbols.size()];
476
                ISymbol[] auxSym = getSymbols();
477

    
478
                for (int i = 0; i < descriptions.length; i++)
479
                        descriptions[i] = auxSym[i].getDescription();
480

    
481
                return descriptions;
482
        }
483

    
484

    
485
        public Object[] getValues() {
486
                return symbols.keySet().toArray();
487
        }
488

    
489
        public void clear() {
490
                index = 0;
491
                keys.clear();
492
                symbols.clear();
493
        }
494

    
495
        public ISymbol[] getSymbols() {
496
                return (ISymbol[]) symbols.values().toArray(new ISymbol[0]);
497
        }
498

    
499
        public String[] getClassifyingFieldNames() {
500
                return fieldNames;
501
        }
502

    
503
        public void setDefaultSymbol(ISymbol s) {
504
                if (s == null) throw new NullPointerException("Default symbol cannot be null");
505
                defaultSymbol = s;
506
        }
507

    
508
        public void setClassifyingFieldNames(String[] fieldNames) {
509
                this.fieldNames = fieldNames;
510
        }
511

    
512
        public ISymbol getDefaultSymbol() {
513
                NullIntervalValue niv=new NullIntervalValue();
514
                if (symbols.containsKey(niv))
515
                        return (ISymbol)symbols.get(niv);
516

    
517
                if(defaultSymbol==null)
518
                    defaultSymbol=SymbologyFactory.createDefaultFillSymbol();//mio
519
                return defaultSymbol;
520
        }
521

    
522
   
523
    public void setDataSource(DataSource ds)
524
        throws FieldNotFoundException, ReadDriverException {
525
            if (!FLyrVect.forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD) {
526
                    /*
527
                     * when we move definitely to feature iterators this
528
                     * method  
529
                     */
530
                    dataSource = ds;
531
                    ds.start();
532
                    fieldId = ds.getFieldIndexByName(fieldNames[0]);
533
                    ds.stop();
534
            } 
535
    }
536

    
537
        
538
        public IInterval getInterval(Value v) {
539
                for (int i = 0; i < keys.size(); i++) {
540
                        if (((IInterval) keys.get(i)).isInInterval(v)) {
541
                                return (IInterval) keys.get(i);
542
                        }
543
                }
544

    
545
                return null;
546
        }
547

    
548
        public void setIntervalType(int intervalType) {
549
                this.intervalType = intervalType;
550
        }
551

    
552
        
553
        public int getIntervalType() {
554
                return intervalType;
555
        }
556

    
557
        public void useDefaultSymbol(boolean b) {
558
                useDefaultSymbol = b;
559
        }
560

    
561

    
562
        public boolean isUseDefaultSymbol() {
563
                return useDefaultSymbol;
564
        }
565

    
566
        
567
        public void delSymbol(Object obj) {
568
                keys.remove(obj);
569
                symbols.remove(obj);
570
        }
571

    
572
        
573
        public void replace(ISymbol oldSymbol, ISymbol newSymbol) {
574
                if (symbols.containsValue(oldSymbol)) {
575
                        Iterator it = symbols.keySet().iterator();
576
                        while (it.hasNext()) {
577
                                Object key = it.next();
578
                                if (symbols.get(key).equals(oldSymbol)) {
579
                                        symbols.remove(key);
580
                                        symbols.put(key, newSymbol);
581
                                }
582
                        }
583
                }
584
        }
585
}