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
/* 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.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
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
54
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
55
import org.gvsig.raster.RasterProcess;
56
import org.gvsig.raster.buffer.BufferFactory;
57
import org.gvsig.raster.buffer.RasterBuffer;
58
import org.gvsig.raster.buffer.WriterBufferServer;
59
import org.gvsig.raster.dataset.GeoRasterWriter;
60
import org.gvsig.raster.dataset.IRasterDataSource;
61
import org.gvsig.raster.dataset.InvalidSetViewException;
62
import org.gvsig.raster.dataset.NotSupportedExtensionException;
63
import org.gvsig.raster.dataset.io.RasterDriverException;
64
import org.gvsig.raster.grid.GridExtent;
65
import org.gvsig.raster.process.CancelEvent;
66
import org.gvsig.raster.util.RasterToolsUtil;
67
import org.gvsig.remotesensing.RemoteSensingUtils;
68
import org.gvsig.remotesensing.gridmath.gui.GridMathPanel;
69
import org.nfunk.jep.JEP;
70
import org.nfunk.jep.Variable;
71

    
72
import com.iver.andami.PluginServices;
73

    
74
/**
75
 * 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
 *
79
 * @author Alejandro Mu�oz Sanchez (alejandro.munoz@uclm.es)
80
 * @author Diego Guerrero Sevilla (diego.guerrero@uclm.es)
81
 * @version 19/10/2007
82
 *
83
 */
84

    
85
public class GridMathProcess extends RasterProcess{
86

    
87
        HashMap                                                 params                                 = null;   // Asignacion de variables a grids.
88
        JEP                                                         parser                                 = null;
89
        String                                                         expression                         = null;
90
        GridExtent                                                 resultExtent                 = null;
91
        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
        private AffineTransform                        aTransform                        = null;
97
        private RasterBuffer                         rasterResult                 = null;
98
        private GridMathPanel                        gridMathPanel                = null;
99
        private boolean                                        loadEnd= false;
100
        int loadBuffers                                        =0;
101
        int numVar                                                =1;
102
        /**
103
         * Constructor
104
         */
105
        public GridMathProcess(){
106
                parser = new JEP();
107
                parser.setAllowUndeclared(true);
108
                parser.addStandardFunctions();
109
        }
110

    
111

    
112
        /**
113
         * @return HashMap con las variables asociadas a sus grid correspondientes
114
         * */
115
        public HashMap getParams() {
116
                return params;
117
        }
118

    
119

    
120
        /**
121
         * Asigna el params con las variables
122
         * @param params
123
         */
124
        public void setParams(HashMap params) {
125
                this.params = params;
126
        }
127

    
128

    
129
        /**
130
         * Establece la expresi�n en el parser
131
         * @param expression expresion
132
         */
133
        public void setExpression(String expression){
134
                this.expression = expression;
135
                parser.getSymbolTable().clear();
136
                parser.parseExpression(expression);
137
        }
138

    
139
        /**
140
         * @return expresi�n a evaluar
141
         */
142
        public String getExpression() {
143
                return expression;
144
        }
145

    
146

    
147
        /**
148
         * @return true si en el parseo de la expresion hay error
149
         */
150
        public boolean hasError(){
151
                if (parser!=null)
152
                        return parser.hasError();
153
                else
154
                        return true;
155
        }
156

    
157

    
158

    
159
        /**
160
        *  Escritura del resultado en disco.
161
        */
162
        private void writeToFile(){
163

    
164
                if(filePath==null)
165
                        return;
166
                try {
167
                        writerBufferServer = new WriterBufferServer(rasterResult);
168
                        aTransform = new AffineTransform(resultExtent.getCellSizeX(), 0.0, 0.0, -resultExtent.getCellSizeY(), resultExtent.getMin().getX(), resultExtent.getMax().getY());
169
                        GeoRasterWriter grw = GeoRasterWriter.getWriter(writerBufferServer, filePath, rasterResult.getBandCount(), aTransform, resultExtent.getNX(), resultExtent.getNY(), rasterResult.getDataType(), GeoRasterWriter.getWriter(filePath).getParams(), mapContext.getProjection());
170
                        grw.dataWrite();
171
                        grw.writeClose();
172
                } catch (NotSupportedExtensionException e) {
173
                        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
                } catch (InterruptedException e) {
177
                        Thread.currentThread().interrupt();
178
                } catch (RasterDriverException e) {
179
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "raster_buffer_invalid_extension"), this, e);
180
                }
181

    
182
                mapContext.beginAtomicEvent();
183
                FLayer lyr = null;
184

    
185
                int endIndex = filePath.lastIndexOf(".");
186
                if (endIndex < 0)
187
                        endIndex = filePath.length();
188

    
189
                try {
190
                         lyr = FLyrRasterSE.createLayer(
191
                                         filePath.substring(filePath.lastIndexOf(File.separator) + 1, endIndex),
192
                                         new File(filePath),
193
                                         mapContext.getProjection());
194
                } catch (LoadLayerException e) {
195
                        RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
196
                }
197

    
198
                mapContext.getLayers().addLayer(lyr);
199
                mapContext.endAtomicEvent();
200
                mapContext.invalidate();
201
                mapContext.endAtomicEvent();
202
        }
203

    
204
        /**
205
         * @return extent del resultadoroot
206
         */
207
        public GridExtent getResultExtent() {
208
                return resultExtent;
209
        }
210

    
211
        /**
212
         * Asignaci�n del extent
213
         * @param resultExtent
214
         */
215
        public void setResultExtent(GridExtent resultExtent) {
216
                this.resultExtent = resultExtent;
217
        }
218

    
219
        /*
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

    
228
        /*
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
                gridMathPanel= (GridMathPanel)getParam("panel");
249
                expression= getStringParam("expresion");
250
                setExpression(expression);
251
                params= (HashMap )getParam("params");
252
                resultExtent= (GridExtent) getParam("extent");
253
                mapContext= (MapContext)getParam("mapcontext");
254
                filePath= getStringParam("filepath");
255
                loadBuffers();
256
        }
257

    
258

    
259
        public void process() throws InterruptedException {
260
                RasterBuffer inputBuffer=null;
261
        
262
                // Construccion del rasterbuffer que recoge el resultado del calculo 
263
                rasterResult = RasterBuffer.getBuffer(RasterBuffer.TYPE_DOUBLE, resultExtent.getNX() ,resultExtent.getNY(), 1, true);
264

    
265
                        
266
                // Calculo de grid resultante
267
                int iNX = resultExtent.getNX();
268
                int iNY = resultExtent.getNY();
269
        
270
                // Calculo de grid resultante
271
                for (int x=0;x<iNX;x++){
272
                        if (cancel) return;  //Proceso cancelado 
273
                        for(int y=0;y<iNY;y++){
274
                                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
                                
280
                                        int dataType= ((Integer)data[1]).intValue();
281
                                        double value=0;
282
                                
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
                                        }else{
293
                                                        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
                                        }
302
                                }
303
                                // Evaluacion de la expresion en el x,y.
304
                                if (i == params.size()){
305
                                        rasterResult.setElem(y, x, 0, (double)parser.getValue());
306
                                        percent = x*100/rasterResult.getWidth();
307
                                }        
308
                        }                
309
        
310
                }
311
                // Escritura de los datos a disco
312
                writeToFile();
313
                
314
        }
315

    
316
        void loadBuffers(){
317

    
318
                int nBand;
319
                String layerBand;
320
                String layerName;
321
                FLyrRasterSE rasterLayer;
322
                FLayers layers = gridMathPanel.getView().getModel().getMapContext().getLayers();
323

    
324
                RasterBuffer valor=null;
325
                int numVar= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount();
326
                for (int i=0;i<numVar;i++){
327

    
328
                        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
                        rasterLayer = (FLyrRasterSE)layers.getLayer(layerName);
332

    
333
                        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

    
339
                        try {
340

    
341
                                IRasterDataSource dsetCopy = null;
342
                                dsetCopy = rasterLayer.getDataSource().newDataset();
343
                                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
344
                                if (!RasterBuffer.loadInMemory(dsetCopy))
345
                                        bufferFactory.setReadOnly(true);
346
                                bufferFactory.setAdjustToExtent(false);
347
                                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

    
352
                        } 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

    
362
                        gridMathPanel.getCalculatorPanel().getQWindowsHash().put(gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,0).toString(),new Object[]{valor,new Integer(valor.getDataType())});
363

    
364
                }
365
                gridMathPanel.getGridMath().setParams(gridMathPanel.getCalculatorPanel().getQWindowsHash());
366

    
367

    
368
                JEP parser = new JEP();
369
                parser.setAllowUndeclared(true);
370
                parser.addStandardFunctions();
371
                parser.parseExpression(gridMathPanel.getCalculatorPanel().getJTextExpression().getText());
372

    
373
                for (Iterator iter = parser.getSymbolTable().values().iterator(); iter.hasNext();) {
374
                        Variable variable = (Variable) iter.next();
375
                        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

    
384

    
385
        public int getPercent(){
386

    
387
                /*if(!loadEnd)
388
                        return (int)((loadBuffers-1)/numVar)*100;
389
                else */if(writerBufferServer!=null)
390
                        return writerBufferServer.getPercent();
391
                else
392
                        return percent;
393
        }
394

    
395

    
396
        /*
397
         * (non-Javadoc)
398
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLog()
399
         */
400
        public String getLog() {
401

    
402
/*                if(!loadEnd)
403
                        return PluginServices.getText(this,"cargando datos")+"...";*/
404
                /*else*/ if (writerBufferServer!=null)
405
                        return PluginServices.getText(this,"escribiendo_resultado")+"...";
406
                else
407
                        return PluginServices.getText(this,"calculando_imagen")+"...";
408
        }
409

    
410

    
411
        public Object getResult(){
412
                return rasterResult;
413
        }
414
}