Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / extRemoteSensing / src / org / gvsig / remotesensing / gridmath / GridMathProcess.java @ 28299

History | View | Annotate | Download (12.6 KB)

1 28299 amunoz
/* gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
2 13790 dguerrero
 *
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 28299 amunoz
 *   Av. Blasco Iba�ez, 50
24 13790 dguerrero
 *   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 26731 vcaballero
import org.gvsig.fmap.mapcontext.MapContext;
50
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
51
import org.gvsig.fmap.mapcontext.layers.FLayer;
52
import org.gvsig.fmap.mapcontext.layers.FLayers;
53 13790 dguerrero
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
54
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
55 18540 nbrodin
import org.gvsig.raster.RasterProcess;
56 22255 amunoz
import org.gvsig.raster.buffer.BufferFactory;
57 13790 dguerrero
import org.gvsig.raster.buffer.RasterBuffer;
58 18855 nbrodin
import org.gvsig.raster.buffer.WriterBufferServer;
59 13790 dguerrero
import org.gvsig.raster.dataset.GeoRasterWriter;
60 22255 amunoz
import org.gvsig.raster.dataset.IRasterDataSource;
61
import org.gvsig.raster.dataset.InvalidSetViewException;
62 13790 dguerrero
import org.gvsig.raster.dataset.NotSupportedExtensionException;
63 16636 amunoz
import org.gvsig.raster.dataset.io.RasterDriverException;
64 13790 dguerrero
import org.gvsig.raster.grid.GridExtent;
65
import org.gvsig.raster.process.CancelEvent;
66 16582 amunoz
import org.gvsig.raster.util.RasterToolsUtil;
67 25518 dguerrero
import org.gvsig.remotesensing.RemoteSensingUtils;
68 22255 amunoz
import org.gvsig.remotesensing.gridmath.gui.GridMathPanel;
69 13790 dguerrero
import org.nfunk.jep.JEP;
70 22255 amunoz
import org.nfunk.jep.Variable;
71 13790 dguerrero
72
import com.iver.andami.PluginServices;
73
74
/**
75 28299 amunoz
 * GridMathProcess implenta la funcionalidad para el c�lculo de operaciones entre grids.
76
 * El proceso permite hacer operaciones matem�ticas entre los valores de las bandas de la misma imagen o entre
77
 * diferentes im�genes bajo ciertas restricciones espaciales (siempre sobre los datos originales).
78 26731 vcaballero
 *
79 28299 amunoz
 * @author Alejandro Mu�oz Sanchez (alejandro.munoz@uclm.es)
80 14804 amunoz
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
81 26731 vcaballero
 * @version 19/10/2007
82 13790 dguerrero
 *
83
 */
84
85 17889 amunoz
public class GridMathProcess extends RasterProcess{
86 26731 vcaballero
87 14518 amunoz
        HashMap                                                 params                                 = null;   // Asignacion de variables a grids.
88
        JEP                                                         parser                                 = null;
89
        String                                                         expression                         = null;
90
        GridExtent                                                 resultExtent                 = null;
91 13790 dguerrero
        private WriterBufferServer                 writerBufferServer        = null;
92
        private int                                         percent                           = 0;
93
        private boolean                                 cancel                                 = false;
94
        private MapContext                                mapContext                        = null;
95
        private String                                        filePath                        = null;
96 14518 amunoz
        private AffineTransform                        aTransform                        = null;
97 26731 vcaballero
        private RasterBuffer                         rasterResult                 = null;
98 22255 amunoz
        private GridMathPanel                        gridMathPanel                = null;
99
        private boolean                                        loadEnd= false;
100
        int loadBuffers                                        =0;
101
        int numVar                                                =1;
102 14803 amunoz
        /**
103
         * Constructor
104
         */
105 14518 amunoz
        public GridMathProcess(){
106 13790 dguerrero
                parser = new JEP();
107
                parser.setAllowUndeclared(true);
108
                parser.addStandardFunctions();
109
        }
110 26731 vcaballero
111
112 13790 dguerrero
        /**
113 26731 vcaballero
         * @return HashMap con las variables asociadas a sus grid correspondientes
114 13790 dguerrero
         * */
115
        public HashMap getParams() {
116
                return params;
117
        }
118 26731 vcaballero
119
120 14803 amunoz
        /**
121
         * Asigna el params con las variables
122 26731 vcaballero
         * @param params
123 14803 amunoz
         */
124 13790 dguerrero
        public void setParams(HashMap params) {
125
                this.params = params;
126
        }
127 26731 vcaballero
128
129 14803 amunoz
        /**
130 28299 amunoz
         * Establece la expresi�n en el parser
131 26731 vcaballero
         * @param expression expresion
132 14803 amunoz
         */
133 13790 dguerrero
        public void setExpression(String expression){
134
                this.expression = expression;
135
                parser.getSymbolTable().clear();
136
                parser.parseExpression(expression);
137
        }
138
139 14803 amunoz
        /**
140 28299 amunoz
         * @return expresi�n a evaluar
141 14803 amunoz
         */
142 13790 dguerrero
        public String getExpression() {
143
                return expression;
144
        }
145 26731 vcaballero
146
147 14803 amunoz
        /**
148
         * @return true si en el parseo de la expresion hay error
149
         */
150 13790 dguerrero
        public boolean hasError(){
151
                if (parser!=null)
152
                        return parser.hasError();
153
                else
154
                        return true;
155
        }
156 26731 vcaballero
157
158
159 13790 dguerrero
        /**
160 17889 amunoz
        *  Escritura del resultado en disco.
161
        */
162
        private void writeToFile(){
163 26731 vcaballero
164 21717 amunoz
                if(filePath==null)
165
                        return;
166 17998 bsanchez
                try {
167 17889 amunoz
                        writerBufferServer = new WriterBufferServer(rasterResult);
168 20826 dguerrero
                        aTransform = new AffineTransform(resultExtent.getCellSizeX(), 0.0, 0.0, -resultExtent.getCellSizeY(), resultExtent.getMin().getX(), resultExtent.getMax().getY());
169 17998 bsanchez
                        GeoRasterWriter grw = GeoRasterWriter.getWriter(writerBufferServer, filePath, rasterResult.getBandCount(), aTransform, resultExtent.getNX(), resultExtent.getNY(), rasterResult.getDataType(), GeoRasterWriter.getWriter(filePath).getParams(), mapContext.getProjection());
170 17889 amunoz
                        grw.dataWrite();
171
                        grw.writeClose();
172 17998 bsanchez
                } catch (NotSupportedExtensionException e) {
173 17889 amunoz
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e);
174
                } catch (IOException e) {
175
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
176 17998 bsanchez
                } catch (InterruptedException e) {
177 17889 amunoz
                        Thread.currentThread().interrupt();
178
                } catch (RasterDriverException e) {
179
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "raster_buffer_invalid_extension"), this, e);
180
                }
181 26731 vcaballero
182 17889 amunoz
                mapContext.beginAtomicEvent();
183
                FLayer lyr = null;
184 26731 vcaballero
185 17889 amunoz
                int endIndex = filePath.lastIndexOf(".");
186
                if (endIndex < 0)
187
                        endIndex = filePath.length();
188 17998 bsanchez
189 17889 amunoz
                try {
190 17998 bsanchez
                         lyr = FLyrRasterSE.createLayer(
191
                                         filePath.substring(filePath.lastIndexOf(File.separator) + 1, endIndex),
192
                                         new File(filePath),
193 18033 bsanchez
                                         mapContext.getProjection());
194 17889 amunoz
                } catch (LoadLayerException e) {
195
                        RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
196 17998 bsanchez
                }
197 17889 amunoz
198
                mapContext.getLayers().addLayer(lyr);
199
                mapContext.endAtomicEvent();
200
                mapContext.invalidate();
201
                mapContext.endAtomicEvent();
202 13790 dguerrero
        }
203 17889 amunoz
204 13790 dguerrero
        /**
205 22260 amunoz
         * @return extent del resultadoroot
206 14803 amunoz
         */
207 17889 amunoz
        public GridExtent getResultExtent() {
208
                return resultExtent;
209
        }
210
211
        /**
212 28299 amunoz
         * Asignaci�n del extent
213 26731 vcaballero
         * @param resultExtent
214 17889 amunoz
         */
215
        public void setResultExtent(GridExtent resultExtent) {
216
                this.resultExtent = resultExtent;
217
        }
218 26731 vcaballero
219 17889 amunoz
        /*
220
         * (non-Javadoc)
221
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
222
         */
223
        public String getLabel() {
224
                return  PluginServices.getText(this,"procesando");
225
        }
226
227 26731 vcaballero
228 17889 amunoz
        /*
229
         * (non-Javadoc)
230
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
231
         */
232
        public String getTitle() {
233
                return PluginServices.getText(this,"band_math");
234
        }
235
236
        /*
237
         * (non-Javadoc)
238
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#actionCanceled
239
         */
240
        public void actionCanceled(IncrementableEvent e) {
241
                if(writerBufferServer != null)
242
                        rasterTask.setEvent(new CancelEvent(this));
243
                cancel = true;
244
        }
245
246
247
        public void init() {
248 22255 amunoz
                gridMathPanel= (GridMathPanel)getParam("panel");
249 17889 amunoz
                expression= getStringParam("expresion");
250
                setExpression(expression);
251
                params= (HashMap )getParam("params");
252
                resultExtent= (GridExtent) getParam("extent");
253 17902 amunoz
                mapContext= (MapContext)getParam("mapcontext");
254 17889 amunoz
                filePath= getStringParam("filepath");
255 22255 amunoz
                loadBuffers();
256 17889 amunoz
        }
257
258
259
        public void process() throws InterruptedException {
260 14866 amunoz
                RasterBuffer inputBuffer=null;
261 28299 amunoz
262
                // Construccion del rasterbuffer que recoge el resultado del calculo
263 20393 dguerrero
                rasterResult = RasterBuffer.getBuffer(RasterBuffer.TYPE_DOUBLE, resultExtent.getNX() ,resultExtent.getNY(), 1, true);
264
265 28299 amunoz
266 20393 dguerrero
                // Calculo de grid resultante
267
                int iNX = resultExtent.getNX();
268
                int iNY = resultExtent.getNY();
269 28299 amunoz
270 20393 dguerrero
                // Calculo de grid resultante
271 25518 dguerrero
                for (int x=0;x<iNX;x++){
272 28299 amunoz
                        if (cancel) return;  //Proceso cancelado
273 25518 dguerrero
                        for(int y=0;y<iNY;y++){
274 20393 dguerrero
                                int i=0;
275
                                for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
276
                                        String varName = (String)iter.next();
277
                                        Object data[]= (Object[])params.get(varName);
278
                                        inputBuffer= (RasterBuffer)data[0];
279 28299 amunoz
280 20393 dguerrero
                                        int dataType= ((Integer)data[1]).intValue();
281
                                        double value=0;
282 28299 amunoz
283
                                        if(dataType==IBuffer.TYPE_BYTE){
284
                                                value =(byte) RemoteSensingUtils.getCellValueInLayerCoords(inputBuffer, x, y, 0);
285
                                                if(value!=inputBuffer.getNoDataValue()){
286
                                                        parser.setVarValue(varName,new Double(value));
287
                                                        i++;
288
                                                }else{
289
                                                        rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
290
                                                        break;
291
                                                }
292 26731 vcaballero
                                        }else{
293 28299 amunoz
                                                        value =RemoteSensingUtils.getCellValueInLayerCoords(inputBuffer, x, y, 0);
294
                                                        if(value!=inputBuffer.getNoDataValue()){
295
                                                                parser.setVarValue(varName,new Double(value));
296
                                                                i++;
297
                                                        }else{
298
                                                                rasterResult.setElem(y, x, 0, rasterResult.noDataValue);
299
                                                                break;
300
                                                        }
301 26731 vcaballero
                                        }
302
                                }
303 28299 amunoz
                                // Evaluacion de la expresion en el x,y.
304 20393 dguerrero
                                if (i == params.size()){
305 25518 dguerrero
                                        rasterResult.setElem(y, x, 0, (double)parser.getValue());
306 28299 amunoz
                                        percent = x*100/rasterResult.getWidth();
307
                                }
308
                        }
309
310 20393 dguerrero
                }
311
                // Escritura de los datos a disco
312
                writeToFile();
313 28299 amunoz
314 14595 amunoz
        }
315 26731 vcaballero
316 22255 amunoz
        void loadBuffers(){
317 26731 vcaballero
318 22255 amunoz
                int nBand;
319
                String layerBand;
320
                String layerName;
321
                FLyrRasterSE rasterLayer;
322
                FLayers layers = gridMathPanel.getView().getModel().getMapContext().getLayers();
323 26731 vcaballero
324 22255 amunoz
                RasterBuffer valor=null;
325
                int numVar= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount();
326
                for (int i=0;i<numVar;i++){
327 26731 vcaballero
328 22255 amunoz
                        layerBand= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,1).toString();
329
                        layerName = layerBand.substring(0,layerBand.indexOf("["));
330
                        nBand = Integer.valueOf(layerBand.substring(layerBand.lastIndexOf("Band")+4,layerBand.lastIndexOf("]"))).intValue();
331 26731 vcaballero
                        rasterLayer = (FLyrRasterSE)layers.getLayer(layerName);
332
333 22255 amunoz
                        double minX=0,minY=0,maxX=0,maxY=0;
334
                        minX= gridMathPanel.getOutputExtent().getMin().getX();
335
                        minY= gridMathPanel.getOutputExtent().getMin().getY();
336
                        maxX= gridMathPanel.getOutputExtent().getMax().getX();
337
                        maxY =gridMathPanel.getOutputExtent().getMax().getY();
338 26731 vcaballero
339 22255 amunoz
                        try {
340 26731 vcaballero
341
                                IRasterDataSource dsetCopy = null;
342 22255 amunoz
                                dsetCopy = rasterLayer.getDataSource().newDataset();
343
                                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
344
                                if (!RasterBuffer.loadInMemory(dsetCopy))
345
                                        bufferFactory.setReadOnly(true);
346 26731 vcaballero
                                bufferFactory.setAdjustToExtent(false);
347 22255 amunoz
                                bufferFactory.setDrawableBands(new int[]{nBand-1});
348
                                bufferFactory.setAreaOfInterest(minX,minY,maxX,maxY,gridMathPanel.getOutputExtent().getNX(),gridMathPanel.getOutputExtent().getNY());
349
                                valor=(RasterBuffer) bufferFactory.getRasterBuf();
350
                                loadBuffers+=1;
351 26731 vcaballero
352 22255 amunoz
                        } catch (ArrayIndexOutOfBoundsException e) {
353
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
354
                        } catch (InvalidSetViewException e) {
355
                                        e.printStackTrace();
356
                        } catch (InterruptedException e) {
357
                                Thread.currentThread().interrupt();
358
                        } catch (RasterDriverException e) {
359
                                e.printStackTrace();
360
                        }
361 26731 vcaballero
362 22255 amunoz
                        gridMathPanel.getCalculatorPanel().getQWindowsHash().put(gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,0).toString(),new Object[]{valor,new Integer(valor.getDataType())});
363 26731 vcaballero
364
                }
365 22255 amunoz
                gridMathPanel.getGridMath().setParams(gridMathPanel.getCalculatorPanel().getQWindowsHash());
366 26731 vcaballero
367
368 22255 amunoz
                JEP parser = new JEP();
369
                parser.setAllowUndeclared(true);
370
                parser.addStandardFunctions();
371
                parser.parseExpression(gridMathPanel.getCalculatorPanel().getJTextExpression().getText());
372 26731 vcaballero
373 22255 amunoz
                for (Iterator iter = parser.getSymbolTable().values().iterator(); iter.hasNext();) {
374 26731 vcaballero
                        Variable variable = (Variable) iter.next();
375 22255 amunoz
                        if (!gridMathPanel.getGridMath().getParams().containsKey(variable.getName())){
376
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"variables_sin_asignar"),this);
377
                                        return;
378
                                }
379
                }
380
                params= gridMathPanel.getGridMath().getParams();
381
                loadEnd= true;
382
        }
383 26731 vcaballero
384
385 22255 amunoz
        public int getPercent(){
386 26731 vcaballero
387 22260 amunoz
                /*if(!loadEnd)
388
                        return (int)((loadBuffers-1)/numVar)*100;
389
                else */if(writerBufferServer!=null)
390 22255 amunoz
                        return writerBufferServer.getPercent();
391
                else
392
                        return percent;
393
        }
394 26731 vcaballero
395
396 22255 amunoz
        /*
397
         * (non-Javadoc)
398
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLog()
399
         */
400
        public String getLog() {
401 26731 vcaballero
402 22260 amunoz
/*                if(!loadEnd)
403
                        return PluginServices.getText(this,"cargando datos")+"...";*/
404
                /*else*/ if (writerBufferServer!=null)
405 22255 amunoz
                        return PluginServices.getText(this,"escribiendo_resultado")+"...";
406
                else
407
                        return PluginServices.getText(this,"calculando_imagen")+"...";
408
        }
409 14803 amunoz
410 22255 amunoz
411 21717 amunoz
        public Object getResult(){
412
                return rasterResult;
413
        }
414 13790 dguerrero
}