Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRemoteSensing / src / org / gvsig / remotesensing / gridmath / GridMathProcess.java @ 20826

History | View | Annotate | Download (10.4 KB)

1 13790 dguerrero
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Iba?ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
 *   Campus Universitario s/n
35
 *   02071 Alabacete
36
 *   Spain
37
 *
38
 *   +34 967 599 200
39
 */
40
41
package org.gvsig.remotesensing.gridmath;
42
43
import java.awt.geom.AffineTransform;
44
import java.io.File;
45
import java.io.IOException;
46
import java.util.HashMap;
47
import java.util.Iterator;
48
49
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
50
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
51 18540 nbrodin
import org.gvsig.raster.RasterProcess;
52 13790 dguerrero
import org.gvsig.raster.buffer.RasterBuffer;
53 18855 nbrodin
import org.gvsig.raster.buffer.WriterBufferServer;
54 13790 dguerrero
import org.gvsig.raster.dataset.GeoRasterWriter;
55
import org.gvsig.raster.dataset.NotSupportedExtensionException;
56 16636 amunoz
import org.gvsig.raster.dataset.io.RasterDriverException;
57 13790 dguerrero
import org.gvsig.raster.grid.GridExtent;
58
import org.gvsig.raster.process.CancelEvent;
59 16582 amunoz
import org.gvsig.raster.util.RasterToolsUtil;
60 13790 dguerrero
import org.nfunk.jep.JEP;
61
import org.nfunk.jep.Variable;
62
63
import com.iver.andami.PluginServices;
64
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
65
import com.iver.cit.gvsig.fmap.MapContext;
66
import com.iver.cit.gvsig.fmap.layers.FLayer;
67
68
/**
69 14804 amunoz
 * GridMathProcess implenta la funcionalidad para el c?lculo de operaciones entre grids.
70
 * El proceso permite hacer operaciones matem?ticas entre los valores de las bandas de la misma imagen o entre
71
 * diferentes im?genes bajo ciertas restricciones espaciales (siempre sobre los datos originales).
72
 *
73
 * @author Alejandro Mu?oz Sanchez (alejandro.munoz@uclm.es)
74
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
75
 * @version 19/10/2007
76 13790 dguerrero
 *
77
 */
78
79 17889 amunoz
public class GridMathProcess extends RasterProcess{
80 13790 dguerrero
81 14518 amunoz
        HashMap                                                 params                                 = null;   // Asignacion de variables a grids.
82
        JEP                                                         parser                                 = null;
83
        String                                                         expression                         = null;
84
        GridExtent                                                 resultExtent                 = null;
85 13790 dguerrero
        private WriterBufferServer                 writerBufferServer        = null;
86
        private int                                         percent                           = 0;
87
        private boolean                                 cancel                                 = false;
88
        private MapContext                                mapContext                        = null;
89
        private String                                        filePath                        = null;
90 14518 amunoz
        private AffineTransform                        aTransform                        = null;
91
        private RasterBuffer                         rasterResult                 = null;
92
93 14803 amunoz
        /**
94
         * Constructor
95
         */
96 14518 amunoz
        public GridMathProcess(){
97 13790 dguerrero
                parser = new JEP();
98
                parser.setAllowUndeclared(true);
99
                parser.addStandardFunctions();
100
        }
101
102
103
        /**
104 14803 amunoz
         * @return HashMap con las variables asociadas a sus grid correspondientes
105 13790 dguerrero
         * */
106
        public HashMap getParams() {
107
                return params;
108
        }
109
110
111 14803 amunoz
        /**
112
         * Asigna el params con las variables
113
         * @param params
114
         */
115 13790 dguerrero
        public void setParams(HashMap params) {
116
                this.params = params;
117
        }
118
119
120 14803 amunoz
        /**
121
         * Establece la expresi?n en el parser
122
         * @param expression expresion
123
         */
124 13790 dguerrero
        public void setExpression(String expression){
125
                this.expression = expression;
126
                parser.getSymbolTable().clear();
127
                parser.parseExpression(expression);
128
        }
129
130 14803 amunoz
        /**
131
         * @return expresi?n a evaluar
132
         */
133 13790 dguerrero
        public String getExpression() {
134
                return expression;
135
        }
136
137
138 14803 amunoz
        /**
139
         * @return true si en el parseo de la expresion hay error
140
         */
141 13790 dguerrero
        public boolean hasError(){
142
                if (parser!=null)
143
                        return parser.hasError();
144
                else
145
                        return true;
146
        }
147
148 17889 amunoz
149
150 13790 dguerrero
        /**
151 17889 amunoz
        *  Escritura del resultado en disco.
152
        */
153
        private void writeToFile(){
154 17998 bsanchez
                try {
155 17889 amunoz
                        writerBufferServer = new WriterBufferServer(rasterResult);
156 20826 dguerrero
                        aTransform = new AffineTransform(resultExtent.getCellSizeX(), 0.0, 0.0, -resultExtent.getCellSizeY(), resultExtent.getMin().getX(), resultExtent.getMax().getY());
157 17998 bsanchez
                        GeoRasterWriter grw = GeoRasterWriter.getWriter(writerBufferServer, filePath, rasterResult.getBandCount(), aTransform, resultExtent.getNX(), resultExtent.getNY(), rasterResult.getDataType(), GeoRasterWriter.getWriter(filePath).getParams(), mapContext.getProjection());
158 17889 amunoz
                        grw.dataWrite();
159
                        grw.writeClose();
160 17998 bsanchez
                } catch (NotSupportedExtensionException e) {
161 17889 amunoz
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e);
162
                } catch (IOException e) {
163
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
164 17998 bsanchez
                } catch (InterruptedException e) {
165 17889 amunoz
                        Thread.currentThread().interrupt();
166
                } catch (RasterDriverException e) {
167
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "raster_buffer_invalid_extension"), this, e);
168
                }
169
170
                mapContext.beginAtomicEvent();
171
                FLayer lyr = null;
172
173
                int endIndex = filePath.lastIndexOf(".");
174
                if (endIndex < 0)
175
                        endIndex = filePath.length();
176 17998 bsanchez
177 17889 amunoz
                try {
178 17998 bsanchez
                         lyr = FLyrRasterSE.createLayer(
179
                                         filePath.substring(filePath.lastIndexOf(File.separator) + 1, endIndex),
180
                                         new File(filePath),
181 18033 bsanchez
                                         mapContext.getProjection());
182 17889 amunoz
                } catch (LoadLayerException e) {
183
                        RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
184 17998 bsanchez
                }
185 17889 amunoz
186
                mapContext.getLayers().addLayer(lyr);
187
                mapContext.endAtomicEvent();
188
                mapContext.invalidate();
189
                mapContext.endAtomicEvent();
190 13790 dguerrero
        }
191 17889 amunoz
192 13790 dguerrero
        /**
193 17889 amunoz
         * @return extent del resultado
194 14803 amunoz
         */
195 17889 amunoz
        public GridExtent getResultExtent() {
196
                return resultExtent;
197
        }
198
199
        /**
200
         * Asignaci?n del extent
201
         * @param resultExtent
202
         */
203
        public void setResultExtent(GridExtent resultExtent) {
204
                this.resultExtent = resultExtent;
205
        }
206 14803 amunoz
207 17889 amunoz
        /*
208
         * (non-Javadoc)
209
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
210
         */
211
        public String getLabel() {
212
                return  PluginServices.getText(this,"procesando");
213
        }
214
215
        /*
216
         * (non-Javadoc)
217
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLog()
218
         */
219
        public String getLog() {
220
                if (writerBufferServer==null)
221
                        return PluginServices.getText(this,"calculando_imagen")+"...";
222
                else
223
                        return PluginServices.getText(this,"escribiendo_resultado")+"...";
224
        }
225
226
227
        /*
228
         * (non-Javadoc)
229
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
230
         */
231
        public int getPercent() {
232
                if (writerBufferServer==null)
233
                        return percent;
234
                else
235
                        return writerBufferServer.getPercent();
236
        }
237
238
239
        /*
240
         * (non-Javadoc)
241
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
242
         */
243
        public String getTitle() {
244
                return PluginServices.getText(this,"band_math");
245
        }
246
247
        /*
248
         * (non-Javadoc)
249
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#actionCanceled
250
         */
251
        public void actionCanceled(IncrementableEvent e) {
252
                if(writerBufferServer != null)
253
                        rasterTask.setEvent(new CancelEvent(this));
254
                cancel = true;
255
        }
256
257
258
        public void init() {
259
                expression= getStringParam("expresion");
260
                setExpression(expression);
261
                params= (HashMap )getParam("params");
262
                resultExtent= (GridExtent) getParam("extent");
263 17902 amunoz
                mapContext= (MapContext)getParam("mapcontext");
264 17889 amunoz
                filePath= getStringParam("filepath");
265
        }
266
267
268
        public void process() throws InterruptedException {
269 14866 amunoz
                RasterBuffer inputBuffer=null;
270 14595 amunoz
271 20393 dguerrero
                // Construccion del rasterbuffer que recoge el resultado del calculo
272
                rasterResult = RasterBuffer.getBuffer(RasterBuffer.TYPE_DOUBLE, resultExtent.getNX() ,resultExtent.getNY(), 1, true);
273
274
275
                // Calculo de grid resultante
276
                int iNX = resultExtent.getNX();
277
                int iNY = resultExtent.getNY();
278 14518 amunoz
279 20393 dguerrero
                // Calculo de grid resultante
280
                for (int x=0;x<iNX;x++){
281
                        if (cancel) return;  //Proceso cancelado
282
                        for(int y=0;y<iNY;y++){
283
                                int i=0;
284
                                for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
285
                                        String varName = (String)iter.next();
286
                                        Object data[]= (Object[])params.get(varName);
287
                                        inputBuffer= (RasterBuffer)data[0];
288 13790 dguerrero
289 20393 dguerrero
                                        int dataType= ((Integer)data[1]).intValue();
290
                                        double value=0;
291
292
                                        //        BUFFER TIPO_BYTE
293
                                        if(dataType == RasterBuffer.TYPE_BYTE){
294
                                                value = inputBuffer.getElemByte(y, x, 0);
295
                                                if(value!=inputBuffer.getNoDataValue()){
296
                                                        parser.setVarValue(varName,new Double(value));
297
                                                        i++;
298
                                                }
299
300
                                                else{
301
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
302
                                                        break;
303
                                                }
304
                                        }
305 14866 amunoz
306 20393 dguerrero
                                        //        BUFFER TIPO_SHORT
307
                                        else if(dataType== RasterBuffer.TYPE_SHORT){
308
                                                value = inputBuffer.getElemShort(y, x, 0);
309
                                                if(value!=inputBuffer.getNoDataValue()){
310
                                                        parser.setVarValue(varName,new Double(value));
311
                                                        i++;
312 14803 amunoz
                                                }
313 20393 dguerrero
                                                else{
314
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
315
                                                        break;
316
                                                        }
317
                                        }
318
319
                                        //        BUFFER TIPO_INT
320
                                        else if(dataType == RasterBuffer.TYPE_INT){
321
                                                value = inputBuffer.getElemInt(y, x,0);
322
                                                if(value!=inputBuffer.getNoDataValue()){
323
                                                        parser.setVarValue(varName,new Double(value));
324
                                                        i++;
325 14803 amunoz
                                                }
326 20393 dguerrero
                                                else{
327
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
328
                                                        break;
329 14803 amunoz
                                                }
330 20393 dguerrero
                                        }
331
332
                                        //        BUFFER TIPO_FLOAT
333
                                        else if(dataType == RasterBuffer.TYPE_FLOAT){
334
                                                value = inputBuffer.getElemFloat(x, y,0);
335
                                                if(value!=inputBuffer.getNoDataValue()){
336 14803 amunoz
                                                                parser.setVarValue(varName,new Double(value));
337
                                                                i++;
338
                                                }
339 20393 dguerrero
                                                else{
340
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
341
                                                        break;
342
                                                        }
343
                                        }
344 14803 amunoz
345 20393 dguerrero
                                        //        BUFFER TIPO_DOUBLE
346
                                        else if(dataType == RasterBuffer.TYPE_DOUBLE){
347
                                                value = inputBuffer.getElemDouble(y, x,0);
348
                                                if(value!=inputBuffer.getNoDataValue()){
349
                                                        parser.setVarValue(varName,new Double(value));
350
                                                        i++;
351
                                                }
352
                                                else{
353
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
354
                                                        break;
355
                                                }
356
                                        }
357
358
                                }
359
                                // Evaluacion de la exprsion en el x,y.
360
                                if (i == params.size()){
361
                                        rasterResult.setElem(y, x, 0, (double)parser.getValue());
362
                                        percent = x*100/rasterResult.getWidth();
363
                                }
364
                        }
365
366
                }
367
                // Escritura de los datos a disco
368
                writeToFile();
369 14866 amunoz
370 14595 amunoz
        }
371 14803 amunoz
372
373 13790 dguerrero
}