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 @ 2308

History | View | Annotate | Download (15.1 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.gvsig.fmap.dal.coverage.RasterLocator;
35
import org.gvsig.fmap.dal.coverage.RasterManager;
36
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
37
import org.gvsig.fmap.dal.coverage.dataset.BufferParam;
38
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
39
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
40
import org.gvsig.fmap.dal.coverage.datastruct.Params;
41
import org.gvsig.fmap.dal.coverage.exception.BufferCreationException;
42
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
43
import org.gvsig.fmap.dal.coverage.exception.QueryException;
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
 * @author Nacho Brodin nachobrodin@gmail.com
60
 */
61
public abstract class ProcessUtils {
62
        protected NoData        doubleNODATA = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(1, Buffer.TYPE_DOUBLE);
63
        
64
        /**
65
         * Registra un mensaje de error en el log de gvSIG
66
         * @param msg Mensaje a guardar en el log
67
         * @param parent Objeto que hizo disparar el mensaje
68
         * @param exception Excepcion que ha sido recogida
69
         */
70
        public void debug(String msg, Object parent, Exception exception) {
71
                if(parent != null)
72
                    LoggerFactory
73
            .getLogger(parent.getClass()).debug(Messages.getText(msg), exception);
74
        }
75
        
76
        /**
77
         * Shows a error dialog with a text and a accept button 
78
         * @param msg Message to show in the dialog
79
         * @param parentWindow Parent window
80
         */
81
        public void messageBoxError(String msg, Object parentWindow){
82
                String string = Messages.getText("accept");
83
                Object[] options = {string};
84
                JOptionPane.showOptionDialog((Component)parentWindow,
85
                                        "<html>" + Messages.getText(msg).replaceAll("\n", "<br>") + "</html>",
86
                                        Messages.getText("confirmacion"),
87
                                        JOptionPane.OK_OPTION,
88
                                        JOptionPane.ERROR_MESSAGE,
89
                                        null,
90
                                        options,
91
                                        string);
92
        }
93
        
94
        /**
95
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. El error es
96
         * registrado en el log de gvSIG con la excepcion que se le pase por parametro
97
         * @param msg Mensaje a mostrar en el dialogo.
98
         * @param parentWindow Ventana desde la que se lanza el dialogo
99
         * @param exception Excepcion que ha sido recogida
100
         */
101
        public void messageBoxError(String msg, Object parentWindow, Exception exception) {
102
                debug(msg, parentWindow, exception);
103
                messageBoxError(msg, parentWindow);
104
        }
105
        
106
        /**
107
         * Muestra un dialogo de error con un texto y un bot?n de aceptar. Se le pasa como ?ltimo par?metros
108
         * una lista de excepciones que ser?n guardadas en el log
109
         * @param msg Mensaje a mostrar en el dialogo.
110
         * @param parentWindow Ventana desde la que se lanza el dialogo
111
         * @param exception Excepcion que ha sido recogida
112
         */
113
        public void messageBoxError(String msg, Object parentWindow, ArrayList<Exception> exception) {
114
                for (int i = 0; i < exception.size(); i++) 
115
                        debug(msg, parentWindow, exception.get(i));
116
                messageBoxError(msg, parentWindow);
117
        }
118
        
119
        /**
120
         * Exports a raster buffer to disk
121
         * @param sFilename
122
         * @param buf
123
         * @param cellsize
124
         * @param minX
125
         * @param minY
126
         * @return
127
         * @throws ProviderNotRegisteredException 
128
         * @throws InitializeException 
129
         */
130
        public boolean exportRaster(final String sFilename, 
131
                        Buffer buf, 
132
                        double cellsize, 
133
                        double minX, 
134
                        double minY,
135
                        NoData nodata) {
136
                boolean result = exportRaster(sFilename, buf, cellsize, minX, minY);
137
                nodata.setFileName(sFilename);
138
                nodata.save();
139
                return result;
140
                /*DataManager manager = DALLocator.getDataManager();
141
                String provider = "Gdal Store";
142
                DataServerExplorerParameters eparams = manager.createServerExplorerParameters("FilesystemExplorer");
143
                
144
                DataServerExplorer serverExplorer = manager.openServerExplorer(eparams.getExplorerName(), eparams);
145

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

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