Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.algorithm / src / main / java / org / gvsig / raster / algorithm / process / ProcessUtils.java @ 2328

History | View | Annotate | Download (16.3 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.algorithm.process;
23

    
24
import java.awt.Component;
25
import java.awt.Rectangle;
26
import java.awt.geom.AffineTransform;
27
import java.awt.geom.Point2D;
28
import java.awt.geom.Rectangle2D;
29
import java.util.ArrayList;
30
import java.util.List;
31

    
32
import javax.swing.JOptionPane;
33

    
34
import org.cresques.cts.IProjection;
35
import org.gvsig.fmap.dal.DALLocator;
36
import org.gvsig.fmap.dal.DataManager;
37
import org.gvsig.fmap.dal.DataServerExplorer;
38
import org.gvsig.fmap.dal.DataServerExplorerParameters;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.RasterManager;
41
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
42
import org.gvsig.fmap.dal.coverage.dataset.BufferParam;
43
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
44
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
45
import org.gvsig.fmap.dal.coverage.datastruct.Params;
46
import org.gvsig.fmap.dal.coverage.exception.BufferCreationException;
47
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
48
import org.gvsig.fmap.dal.coverage.exception.QueryException;
49
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
50
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
51
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
52
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
53
import org.gvsig.fmap.dal.coverage.store.parameter.NewRasterStoreParameters;
54
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
55
import org.gvsig.fmap.dal.exception.DataException;
56
import org.gvsig.fmap.dal.exception.InitializeException;
57
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
58
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
59
import org.gvsig.i18n.Messages;
60
import org.gvsig.raster.roi.ROI;
61
import org.slf4j.Logger;
62
import org.slf4j.LoggerFactory;
63
/**
64
 * Clase base de todos los procesos raster. En ella se genstionan todas las
65
 * funciones comunes como incremento de la tarea, gesti?n de eventos a la tarea, 
66
 * par?metros de la tarea, etc ...
67
 * 
68
 * @author Nacho Brodin nachobrodin@gmail.com
69
 */
70
public abstract class ProcessUtils {
71
        private Logger          log          = LoggerFactory.getLogger(ProcessUtils.class);
72
        protected NoData        doubleNODATA = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(1, Buffer.TYPE_DOUBLE);
73
        
74
        /**
75
         * Registra un mensaje de error en el log de gvSIG
76
         * @param msg Mensaje a guardar en el log
77
         * @param parent Objeto que hizo disparar el mensaje
78
         * @param exception Excepcion que ha sido recogida
79
         */
80
        public void debug(String msg, Object parent, Exception exception) {
81
                if(parent != null)
82
                    LoggerFactory
83
            .getLogger(parent.getClass()).debug(Messages.getText(msg), exception);
84
        }
85
        
86
        /**
87
         * Shows a error dialog with a text and a accept button 
88
         * @param msg Message to show in the dialog
89
         * @param parentWindow Parent window
90
         */
91
        public void messageBoxError(String msg, Object parentWindow){
92
                String string = Messages.getText("accept");
93
                Object[] options = {string};
94
                JOptionPane.showOptionDialog((Component)parentWindow,
95
                                        "<html>" + Messages.getText(msg).replaceAll("\n", "<br>") + "</html>",
96
                                        Messages.getText("confirmacion"),
97
                                        JOptionPane.OK_OPTION,
98
                                        JOptionPane.ERROR_MESSAGE,
99
                                        null,
100
                                        options,
101
                                        string);
102
        }
103
        
104
        /**
105
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. El error es
106
         * registrado en el log de gvSIG con la excepcion que se le pase por parametro
107
         * @param msg Mensaje a mostrar en el dialogo.
108
         * @param parentWindow Ventana desde la que se lanza el dialogo
109
         * @param exception Excepcion que ha sido recogida
110
         */
111
        public void messageBoxError(String msg, Object parentWindow, Exception exception) {
112
                debug(msg, parentWindow, exception);
113
                messageBoxError(msg, parentWindow);
114
        }
115
        
116
        /**
117
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. Se le pasa como ?ltimo par?metros
118
         * una lista de excepciones que ser?n guardadas en el log
119
         * @param msg Mensaje a mostrar en el dialogo.
120
         * @param parentWindow Ventana desde la que se lanza el dialogo
121
         * @param exception Excepcion que ha sido recogida
122
         */
123
        public void messageBoxError(String msg, Object parentWindow, ArrayList<Exception> exception) {
124
                for (int i = 0; i < exception.size(); i++) 
125
                        debug(msg, parentWindow, exception.get(i));
126
                messageBoxError(msg, parentWindow);
127
        }
128
        
129
        /**
130
         * Exports a raster buffer to disk
131
         * @param sFilename
132
         * @param buf
133
         * @param cellsize
134
         * @param minX
135
         * @param minY
136
         * @return
137
         * @throws ProviderNotRegisteredException 
138
         * @throws InitializeException 
139
         */
140
        public void exportRaster(final String sFilename, 
141
                        Buffer buf, 
142
                        ColorInterpretation ci,
143
                        Extent windowExtent,
144
                        NoData nodata,
145
                        IProjection proj) {
146
                nodata.setFileName(sFilename);
147
                nodata.save();
148
                
149
                buf.setDataExtent(windowExtent.toRectangle2D());
150
                
151
                DataManager manager = DALLocator.getDataManager();
152
                String provider = "Gdal Store";
153
                try {
154
                        DataServerExplorerParameters eparams = manager.createServerExplorerParameters("FilesystemExplorer");
155
                        DataServerExplorer serverExplorer = manager.openServerExplorer(eparams.getExplorerName(), eparams);
156

    
157
                        NewRasterStoreParameters sparams = (NewRasterStoreParameters)serverExplorer.getAddParameters(provider);
158
                        sparams.setBuffer(buf);
159
                        sparams.setColorInterpretation(ci.getValues());
160
                        sparams.setProjection(proj);
161
                        sparams.setDestination(sFilename);
162
                        
163
                        serverExplorer.add("Gdal Store", sparams, true);
164
                } catch (InitializeException e) {
165
                        log.debug("Error saving the file of the process", e);
166
                } catch (ProviderNotRegisteredException e) {
167
                        log.debug("Error saving the file of the process", e);
168
                } catch (ValidateDataParametersException e) {
169
                        log.debug("Error saving the file of the process", e);
170
                } catch (DataException e) {
171
                        log.debug("Error saving the file of the process", e);
172
                }
173
        }
174
        
175
        /**
176
         * Exports a raster buffer to disk
177
         * @param sFilename
178
         * @param buf
179
         * @param cellsize
180
         * @param minX
181
         * @param minY
182
         * @return
183
         * @throws ProviderNotRegisteredException 
184
         * @throws InitializeException 
185
         */
186
        public boolean exportRaster(final String sFilename, 
187
                        Buffer buf, 
188
                        double cellsize, 
189
                        double minX, 
190
                        double minY,
191
                        NoData nodata) {
192
                boolean result = exportRaster(sFilename, buf, cellsize, minX, minY);
193
                nodata.setFileName(sFilename);
194
                nodata.save();
195
                return result;
196
        }
197
        
198
        /**
199
         * Exports a raster buffer to disk
200
         * @param sFilename
201
         * @param buf
202
         * @param cellsize
203
         * @param minX
204
         * @param minY
205
         * @return
206
         */
207
        @SuppressWarnings("deprecation")
208
        public boolean exportRaster(final String sFilename, 
209
                        Buffer buf, 
210
                        Buffer alphaBuffer, 
211
                        double cellsize, 
212
                        double ulx, 
213
                        double uly) {
214
                try {
215
                        RasterManager manager = RasterLocator.getManager();
216
                        final DataServerWriter writerBufferServer = manager.createDataServerWriter();
217
                        writerBufferServer.setBuffer(buf, -1);
218
                        int nBands = buf.getBandCount();
219
                        ColorInterpretation colorInterpretation = null;
220
                        if(alphaBuffer != null) {
221
                                colorInterpretation = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
222
                                                new String[] { 
223
                                                                ColorInterpretation.RED_BAND, 
224
                                                                ColorInterpretation.GREEN_BAND, 
225
                                                                ColorInterpretation.BLUE_BAND,
226
                                                                ColorInterpretation.ALPHA_BAND});
227
                        } else {
228
                                if(nBands == 1)
229
                                        colorInterpretation = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
230
                                                        new String[] { ColorInterpretation.GRAY_BAND });
231
                        }
232
                        final Params params = manager.createWriterParams(sFilename);
233
                        final AffineTransform affineTransform =
234
                                new AffineTransform(cellsize, 0, 0,
235
                                                -cellsize, ulx, uly);
236

    
237
                        final RasterWriter writer = manager.createWriter(
238
                                                writerBufferServer, 
239
                                                sFilename,
240
                                                nBands, 
241
                                                affineTransform, 
242
                                                buf.getWidth(),
243
                                                buf.getHeight(), 
244
                                                buf.getDataType(), 
245
                                                params, 
246
                                                null);
247
                        if(colorInterpretation != null)
248
                                writer.setColorBandsInterpretation(colorInterpretation.getValues());
249
                        writer.dataWrite();
250
                        writer.writeClose();
251
                } catch (final Exception e) {
252
                        e.printStackTrace();
253
                        return false;
254
                }
255
                return true;
256
        }
257
        
258
        /**
259
         * Exports a raster buffer to disk
260
         * @param sFilename
261
         * @param buf
262
         * @param cellsize
263
         * @param minX
264
         * @param minY
265
         * @return
266
         */
267
        public boolean exportRaster(final String sFilename, 
268
                        Buffer buf, 
269
                        double cellsize, 
270
                        double ulx, 
271
                        double uly) {
272
        return exportRaster(sFilename, buf, null, cellsize, ulx, uly);
273
    }
274
        
275
        /**
276
         * Gets a list of rectangles which represents the pixel coordinates of each DataStore.
277
         * This rectangle is the area that intersects with the other DataStores in the         list.
278
         * @param dataStoreList
279
         * @return
280
         */
281
        protected Rectangle2D[] getIntersectionInPxCoords(RasterDataStore[] dataStoreList) {
282
                Extent extentIntersect = null;
283
                int nRectangles = 0;
284
                for (int i = 0; i < dataStoreList.length; i++) {
285
                        if(dataStoreList[i] != null) {
286
                                if(extentIntersect == null)
287
                                        extentIntersect = dataStoreList[i].getExtent();
288
                                else
289
                                        extentIntersect = extentIntersect.intersection(dataStoreList[i].getExtent());
290
                                nRectangles ++;
291
                        }
292
                }
293
                Rectangle2D[] result = new Rectangle2D[nRectangles];
294
                
295
                Point2D p1 = new Point2D.Double(extentIntersect.getULX(), extentIntersect.getULY());
296
                Point2D p2 = new Point2D.Double(extentIntersect.getLRX(), extentIntersect.getLRY());
297
                
298
                int cont = 0;
299
                for (int i = 0; i < dataStoreList.length; i++) {
300
                        if(dataStoreList[i] != null) {
301
                                Point2D init = dataStoreList[i].worldToRaster(p1);
302
                                Point2D end = dataStoreList[i].worldToRaster(p2);
303
                                result[cont] = new Rectangle2D.Double(
304
                                                init.getX(), 
305
                                                init.getY(), 
306
                                                Math.abs(end.getX() - init.getX()), 
307
                                                Math.abs(end.getY() - init.getY()));
308
                                cont++;
309
                        }
310
                }
311
                return result;
312
        }
313
        
314
        /**
315
         * Checks if the point in pixel coordinates is inside the region of 
316
         * interest or not. The point will be
317
         * @param x 
318
         * @param y
319
         * @param rois
320
         * @param extentResult
321
         *       Bounding box of the area to which belongs the point defined in pixel coordinates (x, y)
322
         * @return
323
         */
324
        public boolean isInsideOfROI(int x, int y, List<ROI> rois, Extent extentResult) {
325
                if(rois == null || rois.size() == 0)
326
                        return true;
327
                
328
                ROI roi = rois.get(0);
329
                int[] shift = getROIAnalysisShift(extentResult, roi.getStore().getExtent(), roi.getStore().getCellSize());
330
                
331
                for (int i = 0; i < rois.size(); i++) {
332
                        if(rois.get(i).isInsideOfPolygon(x + shift[0], y + shift[1]))
333
                                return true;
334
                }
335
                return false;
336
        }
337
        
338
        /**
339
         * Gets the shift in pixels between the source bounding box and the result bounding box.
340
         * This is useful to get if a pixel is inside a region of interest because the ROI has 
341
         * associate the source. 
342
         * @param extentResult
343
         * @param sourceExtent
344
         * @return
345
         */
346
        private int[] getROIAnalysisShift(Extent extentResult, Extent sourceExtent, double cellsize) {
347
                double xDistance = Math.abs(extentResult.getULX() - sourceExtent.getULX());
348
                double yDistance = Math.abs(extentResult.getULY() - sourceExtent.getULY());
349
                return new int[]{(int)(xDistance / cellsize), (int)(yDistance / cellsize)};
350
        }
351
        
352
        /**
353
         * Gets the bounding box taking into account whether there are ROIs or not
354
         * @return
355
         */
356
        public Extent getExtentResult(Extent window, List<ROI> rois, RasterDataStore store) {
357
                if(window != null)
358
                        return window.intersection(store.getExtent());
359
                if(rois == null)
360
                        return store.getExtent();
361
                else {
362
                        Extent maxExtent = null;
363
                        for (int i = 0; i < rois.size(); i++) {
364
                                if(i == 0)
365
                                        maxExtent = rois.get(i).getROIExtent();
366
                                else
367
                                        maxExtent = maxExtent.encloseBoundinBoxes(rois.get(i).getROIExtent());
368
                        }
369
                        return maxExtent.intersection(store.getExtent());
370
                }
371
        }
372
        
373
        /**
374
         * Returns true if the algorithm is applied to the entire layer
375
         * @param extent
376
         * @param rois
377
         * @param store
378
         * @return
379
         */
380
        public boolean isAnalizedEntireLayer(Extent window, List<ROI> rois, RasterDataStore store) {
381
                if(window == null) {
382
                        if(rois == null || rois.size() == 0)
383
                                return true;
384
                }
385
                return false;
386
        }
387
        
388
        /**
389
         * Gets the bounding box of the source in pixel coordinates
390
         * @param resultExtent
391
         * @return
392
         */
393
        public Rectangle2D getSourcePxBox(Extent resultExtent, RasterDataStore store) {
394
                if(resultExtent == null || resultExtent.equals(store.getExtent()))
395
                        return new Rectangle2D.Double(0, 0, store.getWidth(), store.getHeight());
396
                Point2D p1 = store.worldToRaster(new Point2D.Double(resultExtent.getULX(), resultExtent.getULY()));
397
                Point2D p2 = store.worldToRaster(new Point2D.Double(resultExtent.getLRX(), resultExtent.getLRY()));
398
                return new Rectangle2D.Double(p1.getX(), p1.getY(), Math.abs(p2.getX() - p1.getX()), Math.abs(p2.getY() - p1.getY()));
399
        }
400
        
401
        /**
402
         * Builds the output buffer
403
         * @param sourcePxBBox
404
         * @param bandCount
405
         * @return
406
         */
407
        public Buffer createOutputBuffer(int w, int h, int bandCount) {
408
                return createOutputBuffer(w, h, bandCount, Buffer.TYPE_DOUBLE);
409
        }
410
        
411
        public Buffer createOutputBuffer(int w, int h, int bandCount, int datatype) {
412
                RasterManager rManager = RasterLocator.getManager();
413
                BufferParam bParams = rManager.getBufferFactory().createBufferParams(
414
                                w, 
415
                                h, 
416
                                bandCount, 
417
                                datatype, 
418
                                true);
419
                Buffer resultBuffer = null;
420
                try {
421
                        resultBuffer = rManager.getBufferFactory().createBuffer(bParams);
422
                } catch (BufferCreationException e) {
423
                        new ProcessException("Error creating the output buffer", e);
424
                }
425
                return resultBuffer;
426
        }
427
        
428
        /**
429
         * Gets a data buffer from a <code>RasterDataStore</code> 
430
     */
431
    public Buffer createSourceBuffer(RasterDataStore store, Rectangle2D sourcePxBBox, boolean[] bands) throws ProcessException {
432
        RasterManager rManager = RasterLocator.getManager();
433
        RasterQuery query = rManager.createQuery();
434
        query.setReadOnly(true);
435
        
436
        int nBands = getNumberOfSelectedBands(bands);
437
        int count = 0;
438
        int[] drawableBands = new int[nBands];
439
        for (int i = 0; i < bands.length; i++) {
440
                        if(bands[i]) {
441
                                drawableBands[count] = i;
442
                                count ++;
443
                        }
444
                }
445
        
446
        query.setDrawableBands(drawableBands);
447
        query.setAreaOfInterest(
448
                        new Rectangle(
449
                        (int)sourcePxBBox.getX(), 
450
                        (int)sourcePxBBox.getY(), 
451
                        (int)sourcePxBBox.getWidth(), 
452
                        (int)sourcePxBBox.getHeight()));
453

    
454
        try {
455
                Buffer buffer = null;
456
                try {
457
                        buffer = store.query(query);
458
                } catch (QueryException e) {
459
                        new ProcessException("Error creating the input buffer", e);
460
                }  
461
                return buffer;
462
        } catch (ProcessInterruptedException e) {
463
        }
464
        return null;
465
    } 
466
    
467
        /**
468
         * Gets the number of the selected bands from a list of boolean values.
469
         * Each element in this list represents a band and true or false if the band
470
         * will be used in the task.
471
         * @param bandsPCs
472
         * @return
473
         */
474
        private int getNumberOfSelectedBands(boolean[] b) {
475
                int bandCount = 0;
476
        for (int i = 0; i < b.length; i++) {
477
                        if(b[i])
478
                                bandCount++;
479
                }
480
        return bandCount;
481
        }
482
        
483
        /**
484
         * Gets a value of the buffer in double format
485
         * @param b
486
         * @param row
487
         * @param col
488
         * @param band
489
         * @return
490
         */
491
        protected double getData(Buffer b, int row, int col, int band) {
492
                if(b.getDataType() == Buffer.TYPE_BYTE) {
493
                        return (double)b.getElemByte(row, col, band);
494
                }
495
                if(b.getDataType() == Buffer.TYPE_DOUBLE) {
496
                        return b.getElemDouble(row, col, band);
497
                }
498
                if(b.getDataType() == Buffer.TYPE_FLOAT) {
499
                        return (double)b.getElemFloat(row, col, band);
500
                }
501
                if(b.getDataType() == Buffer.TYPE_INT) {
502
                        return (double)b.getElemInt(row, col, band);
503
                }
504
                if(b.getDataType() == Buffer.TYPE_SHORT) {
505
                        return (double)b.getElemShort(row, col, band);
506
                }
507
                
508
                return doubleNODATA.getValue().doubleValue();
509
        }
510
}