Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / trunk / org.gvsig.raster.tools / org.gvsig.raster.tools.app / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / tool / histogram / HistogramPanelListener.java @ 1435

History | View | Annotate | Download (17 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
package org.gvsig.raster.tools.app.basic.tool.histogram;
20

    
21
import java.awt.Color;
22
import java.awt.event.ActionEvent;
23
import java.awt.event.ActionListener;
24
import java.beans.PropertyChangeEvent;
25
import java.beans.PropertyChangeListener;
26
import java.io.File;
27
import java.util.ArrayList;
28

    
29
import javax.swing.JButton;
30
import javax.swing.JComboBox;
31
import javax.swing.JFileChooser;
32
import javax.swing.JOptionPane;
33
import javax.swing.table.DefaultTableModel;
34

    
35
import org.gvsig.app.ApplicationLocator;
36
import org.gvsig.app.ApplicationManager;
37
import org.gvsig.app.project.documents.table.TableDocument;
38
import org.gvsig.app.project.documents.table.TableManager;
39
import org.gvsig.fmap.dal.DALLocator;
40
import org.gvsig.fmap.dal.DataManager;
41
import org.gvsig.fmap.dal.DataServerExplorer;
42
import org.gvsig.fmap.dal.DataServerExplorerParameters;
43
import org.gvsig.fmap.dal.coverage.RasterLocator;
44
import org.gvsig.fmap.dal.coverage.datastruct.BufferHistogram;
45
import org.gvsig.fmap.dal.coverage.datastruct.HistogramClass;
46
import org.gvsig.fmap.dal.coverage.exception.HistogramException;
47
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
48
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
49
import org.gvsig.fmap.dal.exception.DataException;
50
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
51
import org.gvsig.fmap.dal.feature.EditableFeature;
52
import org.gvsig.fmap.dal.feature.EditableFeatureType;
53
import org.gvsig.fmap.dal.feature.FeatureStore;
54
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
55
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
56
import org.gvsig.gui.beans.graphic.GraphicEvent;
57
import org.gvsig.gui.beans.graphic.GraphicListener;
58
import org.gvsig.raster.fmap.layers.FLyrRaster;
59
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
60
import org.gvsig.raster.tools.app.basic.raster.process.HistogramProcess;
61
import org.gvsig.raster.tools.app.basic.raster.process.IProcessActions;
62
import org.gvsig.raster.tools.app.basic.raster.process.StatisticsProcess;
63
import org.gvsig.raster.tools.app.basic.tool.histogram.ui.HistogramPanel;
64
import org.gvsig.tools.dataTypes.DataTypes;
65
/**
66
 * Listener para eventos del panel de histograma
67
 *
68
 * @version 20/03/2007
69
 * @author Nacho Brodin (brodin_ign@gva.es)
70
 * @author BorSanZa - Borja Sanchez Zamorano (borja.sanchez@iver.es)
71
 */
72
public class HistogramPanelListener implements GraphicListener, ActionListener, PropertyChangeListener, IProcessActions {
73
        private HistogramPanel histogramPanel    = null;
74

    
75
        /**
76
         * Variable que apunta a uno de los dos histogramas posibles: Real o RGB
77
         */
78
        private BufferHistogram      lastHistogram     = null;
79

    
80
        /**
81
         * Histograma original sin convertir a RGB
82
         */
83
        private BufferHistogram      lastHistogramReal = null;
84

    
85
        /**
86
         * Histograma convertido a rango RGB
87
         */
88
        private BufferHistogram      lastHistogramRGB  = null;
89

    
90
        public boolean         eventsEnabled     = false;
91

    
92
        /**
93
         * Bandas que se est?n mostrando en el gr?fico. Se inicializa con las 3 bandas
94
         * RGB de la visualizaci?n. Este array puede tener m?s elementos ya que si las
95
         * bandas no son de visualizaci?n (bandas de la imagen en disco) tendr? un
96
         * elemento por cada una.
97
         */
98
        private boolean[]      showBands         = null;
99
        private FLyrRaster     lyr               = null;
100

    
101
        private Color[]                                                bandsColor     = {
102
                        Color.red,
103
                        Color.green,
104
                        Color.blue,
105
                        Color.cyan,
106
                        Color.black,
107
                        Color.darkGray,
108
                        Color.gray,
109
                        Color.magenta,
110
                        Color.yellow,
111
                        Color.orange};
112

    
113
        /**
114
         * Guardamos el histogramable para hacer el histogramProcess
115
         */
116
        HistogramComputer histogramable = null;
117

    
118
        /**
119
         * Constructor. Asigna el panel del histograma
120
         * @param p Panel
121
         */
122
        public HistogramPanelListener(HistogramPanel histogramPanel) {
123
                this.histogramPanel = histogramPanel;
124
        }
125

    
126
        /**
127
         * Obtiene el panel del histograma
128
         * @return HistogramPanel
129
         */
130
        private HistogramPanel getHistogramPanel() {
131
                return histogramPanel;
132
        }
133

    
134
        /**
135
         * Asigna la capa para obtener las fuentes de datos tanto del
136
         * datasource como de la visualizaci?n.
137
         * @param lyr Capa
138
         */
139
        public void setLayer(FLyrRaster lyr) {
140
                this.lyr = lyr;
141
        }
142

    
143
        public void setControlListeners() {
144
                getHistogramPanel().getGraphicContainer().addValueChangedListener(this);
145
        }
146

    
147
        /**
148
         * Actualizar cuadro de estad?sticas
149
         */
150
        private void updateStatistic() {
151
                if (getLastHistogram() == null) {
152
                        getHistogramPanel().setStatistic(null);
153
                        return;
154
                }
155

    
156
                double first = getHistogramPanel().getGraphicContainer().getX1();
157
                double end = getHistogramPanel().getGraphicContainer().getX2();
158

    
159
                getHistogramPanel().setStatistic(getLastHistogram().getBasicStats(first, end, showBands));
160
        }
161

    
162
        /**
163
         * Tratamiento de todos los eventos visuales.
164
         */
165
        @SuppressWarnings("unchecked")
166
        public void actionPerformed(ActionEvent e) {
167
                if (!eventsEnabled) return;
168

    
169
                // Boton de desmarcar todas las bandas
170
                if (e.getSource() == getHistogramPanel().getButtonClean()) {
171
                        getHistogramPanel().refreshBands(false);
172
                        for (int i = 0; i < showBands.length; i++)
173
                                showBands[i] = false;
174
                        updateStatistic();
175
                        updateGraphic();
176
                        return;
177
                }
178

    
179
                // Boton de marcar todas las bandas
180
                if (e.getSource() == getHistogramPanel().getButtonShowAll()) {
181
                        getHistogramPanel().refreshBands(true);
182
                        for (int i = 0; i < showBands.length; i++)
183
                                showBands[i] = true;
184
                        updateStatistic();
185
                        updateGraphic();
186
                        return;
187
                }
188

    
189
                //--------------------------------------
190
                //Selecci?n de fuente de datos del histograma
191
                JComboBox cbo = getHistogramPanel().getComboBoxSource();
192
                if (e.getSource() == cbo) {
193
                        ArrayList comboSource = getHistogramPanel().getComboSource();
194
                        for (int i = 0; i < comboSource.size(); i++) {
195
                                String name = (String) ((ArrayList) comboSource.get(i)).get(1);
196
                                if (name.compareTo(RasterToolsUtil.getText(this, "datos_visualizados")) == 0) {
197
                                        ((ArrayList) comboSource.get(i)).remove(0);
198
                                        ((ArrayList) comboSource.get(i)).add(0, ((FLyrRaster) lyr).getRender().getLastRenderBuffer().getHistogramComputer());
199

    
200
                                }
201
                                if (name.compareTo(RasterToolsUtil.getText(this, "imagen_completa")) == 0) {
202
                                        ((ArrayList) comboSource.get(i)).remove(0);
203
                                        ((ArrayList) comboSource.get(i)).add(0, ((FLyrRaster) lyr).getDataStore().getHistogramComputer());
204
                                }
205
                        }
206
                        showHistogram();
207
                        return;
208
                }
209

    
210
                // Checkbox de eliminas extremos
211
                if (e.getSource() == getHistogramPanel().getCheckBoxDeleteEdges()) {
212
                        updateGraphic();
213
                        return;
214
                }
215

    
216
                // Checkbox de RGB
217
                if (e.getSource() == getHistogramPanel().getCheckBoxRGB()) {
218
                        selectHistogram();
219
                        updateStatistic();
220
                        updateGraphic();
221
                        return;
222
                }
223

    
224
                //--------------------------------------
225
                //Selecci?n de histograma acumulado y no acumulado
226
                JComboBox cbt = getHistogramPanel().getComboBoxType();
227
                if (e.getSource() == cbt) {
228
                        getHistogramPanel().getGraphicContainer().getPGraphic().setViewType(getHistogramPanel().getComboBoxType().getSelectedIndex());
229
                        return;
230
                }
231

    
232
                //--------------------------------------
233
                // Boton Crear Tabla
234
                JButton table = getHistogramPanel().getBCreateTable();
235
                if (e.getSource() == table) {
236
                        
237
                                //-------Mostrar un fileChooser------------------
238
                                String fName;
239
                                JFileChooser chooser = new JFileChooser();
240
                                chooser.setDialogTitle(RasterToolsUtil.getText(this, "guardar_tabla"));
241

    
242
                                int returnVal = chooser.showOpenDialog(getHistogramPanel());
243
                                if (returnVal == JFileChooser.APPROVE_OPTION) {
244
                                        fName = chooser.getSelectedFile().toString();
245
                                        if (!fName.endsWith(".dbf"))
246
                                                fName += ".dbf";
247

    
248
                                        //-------------Crear el dbf----------------------
249

    
250
                                        HistogramClass[][] histogram = getLastHistogram().getHistogram();
251
                                        int numBands = histogram.length;
252
                                        int numRecors = histogram[0].length;
253

    
254
                                        File file = new File(fName);
255

    
256
                                        String names[] = new String[numBands + 1];
257
                                        int types[] = new int [numBands + 1];
258
                                        int lengths[] = new int [numBands + 1];
259

    
260
                                        names[0] = "Value";
261
                                        types[0] = DataTypes.INT;
262
                                        lengths[0] = 15;
263
                                        for (int band = 0; band < numBands; band++) {
264
                                                names[band + 1] = "Band" + band;
265
                                                types[band + 1] = DataTypes.DOUBLE;
266
                                                lengths[band + 1] = 15;
267
                                        }
268
                                        FeatureStore store = null;
269
                                        
270
                                        try {
271
                                                DataManager manager = DALLocator.getDataManager();
272
                                                DataServerExplorerParameters eparams = manager.createServerExplorerParameters("FilesystemExplorer");
273
                                                eparams.setDynValue("initialpath", "/data");
274
                                                DataServerExplorer serverExplorer = manager.openServerExplorer("FilesystemExplorer", eparams);
275

    
276
                                                NewFeatureStoreParameters sparams = (NewFeatureStoreParameters)serverExplorer.getAddParameters("DBF");
277
                                                ((FilesystemStoreParameters) sparams).setFile(file);
278
                                                
279
                                                EditableFeatureType featureType = sparams.getDefaultFeatureType();
280
                                                
281
                                                //Creating table structure
282
                                                for (int i = 0; i < names.length; i++) {
283
                                                        featureType.add(names[i], types[i], lengths[i]);
284
                                                }
285
                                                
286
                                                manager.newStore("FilesystemExplorer", "DBF", sparams, true);
287
                                                store = (FeatureStore)manager.openStore(sparams.getDataStoreName(), sparams);
288

    
289
                                                //Loading data
290
                                                store.edit();
291
                                                
292
                                                for (int j = 0; j < numRecors; j++) {
293
                                                        EditableFeature feature = store.createNewFeature();
294
                                                        feature.set(names[0], j);
295
                                                        
296
                                                        for (int r = 0; r < numBands; r++) {
297
                                                                feature.set(names[r + 1], histogram[r][j].getValue());
298
                                                        }
299
                                                        store.insert(feature);
300
                                                }
301
                                                
302
                                                store.finishEditing();
303
                                        } catch (DataException e1) {
304
                                                JOptionPane.showMessageDialog(null, getHistogramPanel().getName() + " " + RasterToolsUtil.getText(this,"table_not_create"));
305
                                        } catch (ValidateDataParametersException e2) {
306
                                                JOptionPane.showMessageDialog(null, getHistogramPanel().getName() + " " + RasterToolsUtil.getText(this,"table_not_create"));
307
                                        }
308
                                        
309
                                        //------------A?adir el dbf al proyecto--------------
310
                                        
311
                                        ApplicationManager application = ApplicationLocator.getManager(); 
312
                                        TableDocument tableDocument = (TableDocument)application.getProjectManager().createDocument(TableManager.TYPENAME, 
313
                                                        "Histogram_"+lyr.getName());
314
                                        tableDocument.setStore(store);
315
                                        application.getCurrentProject().add(tableDocument);
316
                                        tableDocument.getFactory().getMainWindow(tableDocument);
317
                                }
318
                }
319
        }
320

    
321
        /**
322
         * Actualizar la variable de las bandas visibles y su componente visual.
323
         */
324
        private void refreshBands() {
325
                getHistogramPanel().refreshBands(true);
326
                if (getLastHistogram() == null)
327
                        showBands = new boolean[0];
328
                else
329
                        showBands = new boolean[getLastHistogram().getNumBands()];
330
                for (int i = 0; i < showBands.length; i++)
331
                        showBands[i] = true;
332
        }
333

    
334
        /**
335
         * Lanza los dos threads para procesar el histograma y visualizar la
336
         * ventana de incremento
337
         */
338
        @SuppressWarnings("unchecked")
339
        public void showHistogram() {
340
                if (getHistogramPanel().getComboBoxSource().getSelectedIndex() < 0)
341
                        return;
342

    
343
                int dataSrc = getHistogramPanel().getComboBoxSource().getSelectedIndex();
344
                histogramable = (HistogramComputer) ((ArrayList) getHistogramPanel().getComboSource().get(dataSrc)).get(0);
345

    
346
                if (getLastHistogram() == null) {
347
                        try {
348
                                if (histogramable != null)
349
                                        setNewHistogram(histogramable.getBufferHistogram());
350
                                else
351
                                        setNewHistogram(null);
352
                        } catch (HistogramException e) {
353
                                RasterToolsUtil.messageBoxError("histogram_error", getHistogramPanel(), e);
354
                                return;
355
                        } catch (ProcessInterruptedException e) {
356
                                
357
                        } 
358
                        return;
359
                }
360

    
361
                // Calculo las estadisticas para luego hacer el proceso del histograma.
362
                // El parametro object es el que se le pasara al siguiente proceso
363
                // Mirar el metodo end()
364
                StatisticsProcess statisticsProcess = new StatisticsProcess();
365
                statisticsProcess.setActions(this);
366
                statisticsProcess.addParam("layer", lyr);
367
                statisticsProcess.addParam("force", Boolean.FALSE);
368
                statisticsProcess.start();
369
        }
370
        
371
        /*
372
         * (non-Javadoc)
373
         * @see org.gvsig.rastertools.IProcessActions#end(java.lang.Object)
374
         */
375
        public void end(Object object) {
376
                // Si tenemos un histograma en el parametro, es que ya ha finalizado el proceso
377
                if (object instanceof BufferHistogram) {
378
                        setNewHistogram((BufferHistogram) object);
379
                        return;
380
                }
381

    
382
                // Si no tenemos un histograma, osease, tenemos un layer, 
383
                // es que aun necesitamos calcularlo
384
                if (object instanceof FLyrRaster) {
385
                        if (histogramable != null) {
386
                                HistogramProcess histogramProcess = new HistogramProcess();
387
                                histogramProcess.setActions(this);
388
                                histogramProcess.addParam("histogramable", histogramable);
389
                                histogramProcess.start();
390
                        } else {
391
                                setNewHistogram(null);
392
                        }
393
                }
394
        }
395

    
396
        /**
397
         * Actualiza la grafica con los datos que ya teniamos del histograma.
398
         */
399
        private void updateGraphic() {
400
                if (getLastHistogram() == null) {
401
                        getHistogramPanel().getGraphicContainer().getPGraphic().cleanChart();
402
                        return;
403
                }
404

    
405
                HistogramClass[][] histogramClass = getLastHistogram().getHistogram();
406
                if (histogramClass == null)
407
                        return;
408

    
409
                double[][][] datos = new double[histogramClass.length][histogramClass[0].length][2];
410
                for (int iBand = 0; iBand < histogramClass.length; iBand++) {
411
                        for (int i = 0; i < histogramClass[iBand].length; i++) {
412
                                datos[iBand][i][0] = histogramClass[iBand][i].getMin();
413
                                datos[iBand][i][1] = histogramClass[iBand][i].getValue();
414
                        }
415
                }
416

    
417
                // Definimos el principio y final de la grafica, sirve para descartar valores.
418
                int first = (int) getHistogramPanel().getBoxValueX1();
419
                int end = (int) getHistogramPanel().getBoxValueX2();
420
                //first = 0;
421
                //end = 100;
422

    
423
                int min = 0;
424
                int max = histogramClass[0].length - 1;
425

    
426
                first = min + ((first * (max - min))/ 100);
427
                end = min + ((end * (max - min))/ 100);
428

    
429
                // Si hay que eliminar los limites, quitamos el ultimo y primer valor de la grafica
430
                if (getHistogramPanel().getCheckBoxDeleteEdges().isSelected()) {
431
                        if ((first + 1) <= end)
432
                                first++;
433
                        if ((end - 1) >= first)
434
                                end--;
435
                }
436

    
437
                int bandCount = 0;
438
                for (int i = 0; i < showBands.length; i++)
439
                        if (showBands[i])
440
                                bandCount++;
441

    
442
                double[][][] newHistogram = new double[bandCount][end - first + 1][2];
443
                String[] bandNames = new String[bandCount];
444

    
445
                int numBand = 0;
446
                for (int iBand = 0; iBand < showBands.length; iBand++) {
447
                        if (!showBands[iBand])
448
                                continue;
449
                        for (int j = first; j <= end; j++) {
450
                                try {
451
                                        newHistogram[numBand][j - first][0] = datos[iBand][j][0];
452
                                        newHistogram[numBand][j - first][1] = datos[iBand][j][1];
453
                                } catch (ArrayIndexOutOfBoundsException e) {
454
                                        RasterToolsUtil.messageBoxError("Error al crear el array del histograma. DataType: " + getHistogramPanel().getDataType() + " Posici?n: " + j, this, e);
455
                                }
456
                        }
457
                        bandNames[numBand] = (String) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(iBand, 1);
458

    
459
                        getHistogramPanel().getGraphicContainer().setBandColor(numBand, bandsColor[iBand % bandsColor.length]);
460

    
461
                        numBand++;
462
                }
463

    
464
                getHistogramPanel().getGraphicContainer().getPGraphic().setNewChart(newHistogram, bandNames);
465
        }
466

    
467

    
468
        public void selectHistogram() {
469
                if (getHistogramPanel().getCheckBoxRGB().isSelected())
470
                        lastHistogram = lastHistogramRGB;
471
                else
472
                        lastHistogram = lastHistogramReal;
473
        }
474
        /**
475
         * Definir el nuevo histograma, metodo pu?blico para ser invocado desde
476
         * histogramProcess
477
         * @param histograma nuevo
478
         */
479
        public void setNewHistogram(BufferHistogram histogram) {
480
                getHistogramPanel().panelInizialited = false;
481
                eventsEnabled = false;
482

    
483
                this.lastHistogramReal = histogram;
484
                this.lastHistogramRGB = RasterLocator.getManager().getRasterUtils().convertHistogramToRGB(lastHistogramReal);
485
                selectHistogram();
486

    
487
                refreshBands();
488
                updateStatistic();
489
                updateGraphic();
490

    
491
                // Activo la ejecucion de los eventos porque seguro que ya tenemos un histograma
492
                eventsEnabled = true;
493
                getHistogramPanel().panelInizialited = true;
494
        }
495

    
496
        /**
497
         * Obtener ?ltimo histograma
498
         * @return Histogram
499
         */
500
        public BufferHistogram getLastHistogram() {
501
                return lastHistogram;
502
        }
503

    
504
        /**
505
         * Eventos de los BoxValues
506
         */
507
        public void actionValueChanged(GraphicEvent e) {
508
                updateStatistic();
509
                updateGraphic();
510
        }
511

    
512
        /**
513
         *  Cuando se selecciona/deselecciona una banda
514
         */
515
        public void propertyChange(PropertyChangeEvent evt) {
516
                if (!eventsEnabled)
517
                        return;
518
                int countRow = ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getRowCount();
519
                for (int i = 0; i < countRow; i++)
520
                        showBands[i] = ((Boolean) ((DefaultTableModel) getHistogramPanel().getJTableBands().getModel()).getValueAt(i, 0)).booleanValue();
521

    
522
                updateStatistic();
523
                updateGraphic();
524
        }
525

    
526
        public void interrupted() {}
527
}