Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.algorithm / src / main / java / org / gvsig / raster / algorithm / process / ProcessUtils.java @ 2129

History | View | Annotate | Download (15.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.geom.AffineTransform;
26
import java.awt.geom.Point2D;
27
import java.awt.geom.Rectangle2D;
28
import java.util.ArrayList;
29
import java.util.List;
30

    
31
import javax.swing.JOptionPane;
32

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

145
                NewRasterStoreParameters sparams = (NewRasterStoreParameters)serverExplorer.getAddParameters(provider);
146
                sparams.setDataServer((DataServerWriter)processIncrement);
147
                sparams.setDestination(path, file);
148
                sparams.setBuffer(buffer);
149
                sparams.setColorInterpretation(new String[]{ColorInterpretation.GRAY_BAND});
150
                sparams.setWktProjection(dstoreCopy.getWktProjection());
151
                sparams.setBand(i);
152
                sparams.setAffineTransform(affineTransform);
153
                sparams.setDriverParams(params);*/
154
        }
155
        
156
        /**
157
         * Exports a raster buffer to disk
158
         * @param sFilename
159
         * @param buf
160
         * @param cellsize
161
         * @param minX
162
         * @param minY
163
         * @return
164
         */
165
        @SuppressWarnings("deprecation")
166
        public boolean exportRaster(final String sFilename, 
167
                        Buffer buf, 
168
                        Buffer alphaBuffer, 
169
                        double cellsize, 
170
                        double minX, 
171
                        double minY) {
172
                try {
173
                        RasterManager manager = RasterLocator.getManager();
174
                        final DataServerWriter writerBufferServer = manager.createDataServerWriter();
175
                        writerBufferServer.setBuffer(buf, -1);
176
                        int nBands = buf.getBandCount();
177
                        ColorInterpretation colorInterpretation = null;
178
                        if(alphaBuffer != null) {
179
                                writerBufferServer.setAlphaBuffer(alphaBuffer);
180
                                nBands ++;
181
                                colorInterpretation = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
182
                                                new String[] { 
183
                                                                ColorInterpretation.RED_BAND, 
184
                                                                ColorInterpretation.GREEN_BAND, 
185
                                                                ColorInterpretation.BLUE_BAND,
186
                                                                ColorInterpretation.ALPHA_BAND});
187
                        } else {
188
                                if(nBands == 1)
189
                                        colorInterpretation = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
190
                                                        new String[] { ColorInterpretation.GRAY_BAND });
191
                        }
192
                        final Params params = manager.createWriterParams(sFilename);
193
                        final AffineTransform affineTransform =
194
                                new AffineTransform(cellsize, 0, 0,
195
                                                -cellsize, minX, minY);
196

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

    
413
        try {
414
                Buffer buffer = null;
415
                try {
416
                        buffer = store.query(query);
417
                } catch (RasterDriverException e) {
418
                        new ProcessException("Error creating the input buffer", e);
419
                }  catch (InvalidSetViewException e) {
420
                        new ProcessException("Error creating the input buffer", e);
421
                } 
422
                return buffer;
423
        } catch (ProcessInterruptedException e) {
424
        }
425
        return null;
426
    } 
427
    
428
        /**
429
         * Gets the number of the selected bands from a list of boolean values.
430
         * Each element in this list represents a band and true or false if the band
431
         * will be used in the task.
432
         * @param bandsPCs
433
         * @return
434
         */
435
        private int getNumberOfSelectedBands(boolean[] b) {
436
                int bandCount = 0;
437
        for (int i = 0; i < b.length; i++) {
438
                        if(b[i])
439
                                bandCount++;
440
                }
441
        return bandCount;
442
        }
443
        
444
        /**
445
         * Gets a value of the buffer in double format
446
         * @param b
447
         * @param row
448
         * @param col
449
         * @param band
450
         * @return
451
         */
452
        protected double getData(Buffer b, int row, int col, int band) {
453
                if(b.getDataType() == Buffer.TYPE_BYTE) {
454
                        return (double)b.getElemByte(row, col, band);
455
                }
456
                if(b.getDataType() == Buffer.TYPE_DOUBLE) {
457
                        return b.getElemDouble(row, col, band);
458
                }
459
                if(b.getDataType() == Buffer.TYPE_FLOAT) {
460
                        return (double)b.getElemFloat(row, col, band);
461
                }
462
                if(b.getDataType() == Buffer.TYPE_INT) {
463
                        return (double)b.getElemInt(row, col, band);
464
                }
465
                if(b.getDataType() == Buffer.TYPE_SHORT) {
466
                        return (double)b.getElemShort(row, col, band);
467
                }
468
                NoData nd = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(1, Buffer.TYPE_DOUBLE);
469
                return nd.getValue().doubleValue();
470
        }
471
}