Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / rendering / legend / AbstractIntervalLegend.java @ 24494

History | View | Annotate | Download (16.2 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 21144 2008-06-03 15:47:31Z vcaballero $
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 org.gvsig.fmap.mapcontext.rendering.legend;
88

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

    
95
import org.apache.log4j.Logger;
96
import org.gvsig.fmap.dal.exceptions.ReadException;
97
import org.gvsig.fmap.dal.feature.Feature;
98
import org.gvsig.fmap.dal.feature.FeatureReference;
99
import org.gvsig.fmap.dal.feature.FeatureStore;
100
import org.gvsig.fmap.dal.feature.FeatureType;
101
import org.gvsig.fmap.mapcontext.Messages;
102
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
103
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
104
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
105
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbologyFactory;
106

    
107

    
108
public abstract class AbstractIntervalLegend extends AbstractClassifiedVectorLegend implements IVectorialIntervalLegend{
109
        protected int shapeType;
110

    
111
        public static final int EQUAL_INTERVALS = 0;
112
        public static final int NATURAL_INTERVALS = 1;
113
        public static final int QUANTILE_INTERVALS = 2;
114
        protected TreeMap symbols = new TreeMap //<Object, ISymbol>
115
                        (new Comparator() { //<Object>
116
                public int compare(Object o1, Object o2) {
117
                        if ((o1 != null) && (o2 != null)) {
118
                                if (o1 instanceof NullIntervalValue &&
119
                                                o2 instanceof NullIntervalValue) {
120
                                        return 0;
121
                                }
122

    
123
                                if (o2 instanceof NullIntervalValue) {
124
                                        return 1;
125
                                }
126

    
127
                                if (o1 instanceof NullIntervalValue) {
128
                                        return -1;
129
                                }
130

    
131
                                FInterval i2 = (FInterval) o2;
132
                                FInterval i1 = (FInterval) o1;
133

    
134
                                if (i1.getMin() > i2.getMin()) {
135
                                        return 1;
136
                                }
137

    
138
                                if (i1.getMin() < i2.getMin()) {
139
                                        return -1;
140
                                }
141
                                if (i1.getMax() < i2.getMax()) {
142
                                        return -1;
143
                                }
144
                                if (i1.getMax() > i2.getMax()) {
145
                                        return 1;
146
                                }
147
                        }
148

    
149
                        return 0;
150
                }
151
        });
152
        protected ArrayList keys = new ArrayList(); //<Object>
153
        protected int index = 0;
154
        protected String[] fieldNames;
155
        protected int fieldId;
156
        protected ISymbol defaultSymbol;
157
        protected FeatureStore featureStore;
158
        protected int intervalType = NATURAL_INTERVALS;
159
        protected boolean useDefaultSymbol = false;
160

    
161
        private Logger logger = Logger.getLogger(AbstractIntervalLegend.class);
162

    
163
        public void addSymbol(Object key, ISymbol symbol) {
164
                symbols.put(key, symbol);
165
                keys.add(key);
166
                fireClassifiedSymbolChangeEvent(new SymbolLegendEvent(null, symbol));
167
        }
168

    
169
        /*
170
         * @see com.iver.cit.gvsig.fmap.rendering.IVectorialLegend#getSymbol(int)
171
         */
172
        public ISymbol getSymbol(FeatureReference featureID) throws ReadException {
173
                Object val = featureStore.getFeatureByReference(featureID).get(fieldId);
174
                IInterval interval = getInterval(val);
175
                ISymbol theSymbol = getSymbolByInterval(interval);
176

    
177

    
178
                if (theSymbol != null) {
179
                        return theSymbol;
180
                } else if (useDefaultSymbol) {
181
                        return getDefaultSymbol();
182
                }
183

    
184
                return null;
185
        }
186

    
187
        public ISymbol getSymbolByFeature(Feature feat) {
188
                Object val = feat.get(fieldId);
189
                IInterval interval = getInterval(val);
190
                ISymbol theSymbol = getSymbolByInterval(interval);
191

    
192
                return theSymbol;
193
        }
194

    
195

    
196
        public FInterval[] calculateIntervals(FeatureStore featureStore, String fieldName, int numIntervalos, int shapeType)
197
        throws ReadException, LegendLayerException {
198
                logger.debug("elRs.start()");
199
//                recordSet.start();
200

    
201
//                int idField = -1;
202

    
203
                setClassifyingFieldNames(new String[] {fieldName});
204

    
205
                String[] fieldNames = getClassifyingFieldNames();
206
                Iterator iterator=featureStore.getDataCollection(fieldNames,null,null).iterator();
207

    
208

    
209
//                for (int i = 0; i < recordSet.getFieldCount(); i++) {
210
//                        String nomAux = recordSet.getFieldName(i).trim();
211
//
212
//                        if (fieldNames[0].compareToIgnoreCase(nomAux) == 0) {
213
//                                idField = i;
214
//
215
//                                break;
216
//                        }
217
//                }
218

    
219
//                if (idField == -1) {
220
//                        logger.error("Campo no reconocido " + fieldNames);
221
//
222
//                        return null;
223
//                }
224

    
225
                double minValue = Double.MAX_VALUE;
226
                double maxValue = Double.NEGATIVE_INFINITY;
227

    
228
                VectorialIntervalLegend auxLegend = LegendFactory.
229
                    createVectorialIntervalLegend(shapeType);
230

    
231
                Object clave;
232

    
233
                while (iterator.hasNext()) {
234
                        Feature feature = (Feature) iterator.next();
235

    
236
//                for (int j = 0; j < recordSet.getRowCount(); j++) {
237
                        clave = feature.get(fieldName);
238

    
239
                        IInterval interval = auxLegend.getInterval(clave);
240

    
241
                        ////Comprobar que no esta repetido y no hace falta introducir en el hashtable el campo junto con el simbolo.
242
                        if (auxLegend.getSymbolByInterval(interval) == null) {
243
                                //si no esta creado el simbolo se crea
244
                                double valor = 0;
245

    
246

    
247
                                if (clave instanceof Number) {
248
                                        valor=((Number)clave).doubleValue();
249
                                }else if (clave instanceof Date) {
250
                                        //TODO POR IMPLEMENTAR
251
                                        ///valorDate = elRs.getFieldValueAsDate(idField);
252
                                        ///if (valorDate.before(minValueDate)) minValueDate = valorDate;
253
                                        ///if (valorDate.after(maxValueDate)) maxValueDate = valorDate;
254
                                } else if (clave instanceof NullValue) {
255
                                        continue;
256
                                }
257

    
258
                                if (valor < minValue) {
259
                                        minValue = valor;
260
                                }
261

    
262
                                if (valor > maxValue) {
263
                                        maxValue = valor;
264
                                }
265
                        }
266
                }
267

    
268
                FInterval[] intervalArray = null;
269
                switch (getIntervalType()) {
270
                case VectorialIntervalLegend.EQUAL_INTERVALS:
271
                        intervalArray = calculateEqualIntervals(numIntervalos,
272
                                        minValue, maxValue, fieldName);
273

    
274
                        break;
275

    
276
                case VectorialIntervalLegend.NATURAL_INTERVALS:
277
                        intervalArray = calculateNaturalIntervals(featureStore, numIntervalos,
278
                                        minValue, maxValue, fieldName);
279

    
280
                        break;
281

    
282
                case VectorialIntervalLegend.QUANTILE_INTERVALS:
283
                        intervalArray = calculateQuantileIntervals(featureStore, numIntervalos,
284
                                        minValue, maxValue, fieldName);
285

    
286
                        break;
287
                }
288
//                recordSet.stop();
289
                return intervalArray;
290
        }
291

    
292

    
293
    /**
294
     * EQUAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
295
     * quieren crear. Los intervalos se crean con un tama?o igual entre ellos.
296
     * @param numIntervals n?mero de intervalos
297
     * @param minValue Valor m?nimo.
298
     * @param maxValue Valor m?ximo.
299
     * @param fieldName Nombre del campo
300
     *
301
     * @return Array con los intervalos.
302
     */
303
    private FInterval[] calculateEqualIntervals(int numIntervals, double minValue,
304
        double maxValue, String fieldName) {
305
        FInterval[] theIntervalArray = new FInterval[numIntervals];
306
        double step = (maxValue - minValue) / numIntervals;
307

    
308
        if (numIntervals > 1) {
309
            theIntervalArray[0] = new FInterval(minValue, minValue + step);
310

    
311
            for (int i = 1; i < (numIntervals - 1); i++) {
312
                theIntervalArray[i] = new FInterval(minValue + (i * step) +
313
                        0.01, minValue + ((i + 1) * step));
314
            }
315

    
316
            theIntervalArray[numIntervals - 1] = new FInterval(minValue +
317
                    ((numIntervals - 1) * step) + 0.01, maxValue);
318
        } else {
319
            theIntervalArray[0] = new FInterval(minValue, maxValue);
320
        }
321

    
322
        return theIntervalArray;
323
    }
324

    
325
    /**
326
     * NATURAL INTERVAL Devuelve un Array con el n?mero de intervalos que se
327
     * quieren crear. Los intervalos se distribuyen de forma natural.
328
     *
329
     * @param numIntervals n?mero de intervalos
330
     * @param minValue Valor m?nimo.
331
     * @param maxValue Valor m?ximo.
332
     * @param fieldName Nombre del campo
333
     *
334
     * @return Array con los intervalos.
335
     * @throws LegendLayerException
336
     */
337
    private FInterval[] calculateNaturalIntervals(FeatureStore featureStore, int numIntervals, double minValue,
338
        double maxValue, String fieldName) throws LegendLayerException {
339
        NaturalIntervalGenerator intervalGenerator = new NaturalIntervalGenerator(
340
                        featureStore, fieldName, numIntervals);
341

    
342
        try {
343
            intervalGenerator.generarIntervalos();
344
        } catch (ReadException e) {
345
                throw new LegendLayerException(Messages.getString("failed_calculating_intervals"), e);
346
        }
347

    
348
        int numIntervalsGen = intervalGenerator.getNumIntervals() - 1;
349

    
350
        if (numIntervalsGen == -1) {
351
            //TODO cuando no puede calcular los intervalos.
352
            numIntervalsGen = 1;
353
        }
354

    
355
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
356

    
357
        if (numIntervalsGen > 1) {
358
            theIntervalArray[0] = new FInterval(minValue,
359
                    intervalGenerator.getValorRuptura(0));
360

    
361
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
362
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
363
                            1), intervalGenerator.getValorRuptura(i));
364
            }
365

    
366
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
367
                        2), maxValue);
368
        } else {
369
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
370
                    maxValue);
371
        }
372

    
373
        return theIntervalArray;
374
    }
375

    
376
    /**
377
     * QUANTILE INTERVAL Devuelve un Array con el n?mero de intervalos que se
378
     * quieren crear. Los intervalos se distribuyen de forma quantile.
379
     * @param recordSet
380
     *
381
     * @param numIntervals n?mero de intervalos
382
     * @param minValue Valor m?nimo.
383
     * @param maxValue Valor m?ximo.
384
     * @param fieldName Nombre del campo
385
     *
386
     * @return Array con los intervalos.
387
     * @throws LegendLayerException
388
     */
389
    private FInterval[] calculateQuantileIntervals(FeatureStore featureStore, int numIntervals, double minValue,
390
        double maxValue, String fieldName) throws LegendLayerException {
391
        QuantileIntervalGenerator intervalGenerator = new QuantileIntervalGenerator(
392
                        featureStore, fieldName, numIntervals);
393

    
394
        try {
395
            intervalGenerator.generarIntervalos();
396
        } catch (ReadException e) {
397
                throw new LegendLayerException(Messages.getString("failed_calculating_intervals"), e);
398
        }
399

    
400
        int numIntervalsGen = intervalGenerator.getNumIntervalGen();
401
        FInterval[] theIntervalArray = new FInterval[numIntervalsGen];
402

    
403
        if (intervalGenerator.getNumIntervalGen() > 1) {
404
            theIntervalArray[0] = new FInterval(minValue,
405
                    intervalGenerator.getValRuptura(0));
406

    
407
            for (int i = 1; i < (numIntervalsGen - 1); i++) {
408
                theIntervalArray[i] = new FInterval(intervalGenerator.getValInit(i -
409
                            1), intervalGenerator.getValRuptura(i));
410
            }
411

    
412
            theIntervalArray[numIntervalsGen - 1] = new FInterval(intervalGenerator.getValInit(numIntervalsGen -
413
                        2), maxValue);
414
        } else {
415
            theIntervalArray[numIntervalsGen - 1] = new FInterval(minValue,
416
                    maxValue);
417
        }
418

    
419
        return theIntervalArray;
420
    }
421

    
422
    public ISymbol getSymbolByInterval(IInterval key) {
423

    
424
                if (key == null){
425
                        if (isUseDefaultSymbol())
426
                                return defaultSymbol;
427
                        return null;
428
                }
429
                if (symbols.containsKey(key)) {
430
                        return (ISymbol) symbols.get(key);
431
                }
432

    
433
                if (isUseDefaultSymbol())
434
                        return defaultSymbol;
435

    
436
                return null;
437
        }
438

    
439

    
440
        public String[] getDescriptions() {
441
                String[] descriptions = new String[symbols.size()];
442
                ISymbol[] auxSym = getSymbols();
443

    
444
                for (int i = 0; i < descriptions.length; i++)
445
                        descriptions[i] = auxSym[i].getDescription();
446

    
447
                return descriptions;
448
        }
449

    
450

    
451
        public Object[] getValues() {
452
                return symbols.keySet().toArray();
453
        }
454

    
455
        public void clear() {
456
                index = 0;
457
                keys.clear();
458
                symbols.clear();
459
        }
460

    
461
        public ISymbol[] getSymbols() {
462
                return (ISymbol[]) symbols.values().toArray(new ISymbol[0]);
463
        }
464

    
465
        public String[] getClassifyingFieldNames() {
466
                return fieldNames;
467
        }
468

    
469
        public void setDefaultSymbol(ISymbol s) {
470
            ISymbol old = defaultSymbol;
471
                if (s == null) throw new NullPointerException("Default symbol cannot be null");
472
                defaultSymbol = s;
473
                fireDefaultSymbolChangedEvent(new SymbolLegendEvent(old, defaultSymbol));
474
        }
475

    
476
        public void setClassifyingFieldNames(String[] fieldNames) {
477
                this.fieldNames = fieldNames;
478
        }
479

    
480
        public ISymbol getDefaultSymbol() {
481
                NullIntervalValue niv=new NullIntervalValue();
482
                if (symbols.containsKey(niv))
483
                        return (ISymbol)symbols.get(niv);
484

    
485
                if(defaultSymbol==null)
486
                        defaultSymbol=SymbologyFactory.createDefaultSymbolByShapeType(shapeType);
487
                return defaultSymbol;
488
        }
489

    
490

    
491

    
492
    public void setFeatureStore(FeatureStore featureStore)
493
        throws ReadException {
494
                    /*
495
                     * when we move definitely to feature iterators this
496
                     * method
497
                     */
498
                    this.featureStore = featureStore;
499
//                    ds.start();
500
                    fieldId = ((FeatureType)featureStore.getFeatureTypes().get(0)).getIndex(fieldNames[0]);
501
//                    ds.stop();
502
    }
503

    
504

    
505
        public IInterval getInterval(Object v) {
506
                for (int i = 0; i < keys.size(); i++) {
507
                        if (((IInterval) keys.get(i)).isInInterval(v)) {
508
                                return (IInterval) keys.get(i);
509
                        }
510
                }
511

    
512
                return null;
513
        }
514

    
515
        public void setIntervalType(int intervalType) {
516
                this.intervalType = intervalType;
517
        }
518

    
519

    
520
        public int getIntervalType() {
521
                return intervalType;
522
        }
523

    
524
        public void useDefaultSymbol(boolean b) {
525
                useDefaultSymbol = b;
526
        }
527

    
528

    
529
        public boolean isUseDefaultSymbol() {
530
                return useDefaultSymbol;
531
        }
532

    
533

    
534
        public void delSymbol(Object obj) {
535
                keys.remove(obj);
536
                symbols.remove(obj);
537
                fireClassifiedSymbolChangeEvent(
538
                                new SymbolLegendEvent(
539
                                                (ISymbol)symbols.remove(obj),
540
                                                null));
541
        }
542

    
543

    
544
        public void replace(ISymbol oldSymbol, ISymbol newSymbol) {
545
                if (symbols.containsValue(oldSymbol)) {
546
                        Iterator it = symbols.keySet().iterator();
547
                        while (it.hasNext()) {
548
                                Object key = it.next();
549
                                if (symbols.get(key).equals(oldSymbol)) {
550
                                        symbols.remove(key);
551
                                        symbols.put(key, newSymbol);
552
                                        fireClassifiedSymbolChangeEvent(
553
                                                        new SymbolLegendEvent(oldSymbol, newSymbol));
554
                                }
555
                        }
556
                }
557
        }
558
}