Statistics
| Revision:

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

History | View | Annotate | Download (12.3 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.raster.layers.FLyrRasterSE;
50
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
51
import org.gvsig.raster.RasterProcess;
52
import org.gvsig.raster.buffer.BufferFactory;
53
import org.gvsig.raster.buffer.RasterBuffer;
54
import org.gvsig.raster.buffer.WriterBufferServer;
55
import org.gvsig.raster.dataset.GeoRasterWriter;
56
import org.gvsig.raster.dataset.IRasterDataSource;
57
import org.gvsig.raster.dataset.InvalidSetViewException;
58
import org.gvsig.raster.dataset.NotSupportedExtensionException;
59
import org.gvsig.raster.dataset.io.RasterDriverException;
60
import org.gvsig.raster.grid.GridExtent;
61
import org.gvsig.raster.process.CancelEvent;
62
import org.gvsig.raster.util.RasterToolsUtil;
63
import org.gvsig.remotesensing.RemoteSensingUtils;
64
import org.gvsig.remotesensing.gridmath.gui.GridMathPanel;
65
import org.nfunk.jep.JEP;
66
import org.nfunk.jep.Variable;
67

    
68
import com.iver.andami.PluginServices;
69
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
70
import com.iver.cit.gvsig.fmap.MapContext;
71
import com.iver.cit.gvsig.fmap.layers.FLayer;
72
import com.iver.cit.gvsig.fmap.layers.FLayers;
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
                                        value = RemoteSensingUtils.getCellValueInLayerCoords(inputBuffer, x, y, 0);                        
284
                                        if(value!=inputBuffer.getNoDataValue()){        
285
                                                parser.setVarValue(varName,new Double(value));
286
                                                i++;                                        
287
                                        }else{                                        
288
                                                rasterResult.setElem(x, y, 0, rasterResult.noDataValue);
289
                                                break;        
290
                                        }        
291
                                }        
292
                                // Evaluacion de la exprsion en el x,y.
293
                                if (i == params.size()){
294
                                        rasterResult.setElem(y, x, 0, (double)parser.getValue());
295
                                        percent = x*100/rasterResult.getHeight();
296
                                }        
297
                        }                
298
        
299
                }
300
                // Escritura de los datos a disco
301
                writeToFile();
302
                
303
        }
304
        
305
        
306
        void loadBuffers(){
307
                
308
                int nBand;
309
                String layerBand;
310
                String layerName;
311
                FLyrRasterSE rasterLayer;
312
                FLayers layers = gridMathPanel.getView().getModel().getMapContext().getLayers();
313
                
314
                RasterBuffer valor=null;
315
                int numVar= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getRowCount();
316
                for (int i=0;i<numVar;i++){
317
                        
318
                        layerBand= gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,1).toString();
319
                        layerName = layerBand.substring(0,layerBand.indexOf("["));
320
                        nBand = Integer.valueOf(layerBand.substring(layerBand.lastIndexOf("Band")+4,layerBand.lastIndexOf("]"))).intValue();
321
                        rasterLayer = (FLyrRasterSE)layers.getLayer(layerName);                
322
                        
323
                        double minX=0,minY=0,maxX=0,maxY=0;
324
                        minX= gridMathPanel.getOutputExtent().getMin().getX();
325
                        minY= gridMathPanel.getOutputExtent().getMin().getY();
326
                        maxX= gridMathPanel.getOutputExtent().getMax().getX();
327
                        maxY =gridMathPanel.getOutputExtent().getMax().getY();
328
                        
329
                        try {
330
                                        
331
                                IRasterDataSource dsetCopy = null; 
332
                                dsetCopy = rasterLayer.getDataSource().newDataset();
333
                                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
334
                                if (!RasterBuffer.loadInMemory(dsetCopy))
335
                                        bufferFactory.setReadOnly(true);
336
                                bufferFactory.setAdjustToExtent(false);                
337
                                bufferFactory.setDrawableBands(new int[]{nBand-1});
338
                                bufferFactory.setAreaOfInterest(minX,minY,maxX,maxY,gridMathPanel.getOutputExtent().getNX(),gridMathPanel.getOutputExtent().getNY());
339
                                valor=(RasterBuffer) bufferFactory.getRasterBuf();
340
                                loadBuffers+=1;
341
                                
342
                        } catch (ArrayIndexOutOfBoundsException e) {
343
                                RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
344
                        } catch (InvalidSetViewException e) {
345
                                        e.printStackTrace();
346
                        } catch (InterruptedException e) {
347
                                Thread.currentThread().interrupt();
348
                        } catch (RasterDriverException e) {
349
                                e.printStackTrace();
350
                        }
351
        
352
                        gridMathPanel.getCalculatorPanel().getQWindowsHash().put(gridMathPanel.getCalculatorPanel().getJTableVariables().getTableFormat().getValueAt(i,0).toString(),new Object[]{valor,new Integer(valor.getDataType())});
353
                        
354
                }                                
355
                gridMathPanel.getGridMath().setParams(gridMathPanel.getCalculatorPanel().getQWindowsHash());
356
        
357
        
358
                JEP parser = new JEP();
359
                parser.setAllowUndeclared(true);
360
                parser.addStandardFunctions();
361
                parser.parseExpression(gridMathPanel.getCalculatorPanel().getJTextExpression().getText());
362
        
363
                for (Iterator iter = parser.getSymbolTable().values().iterator(); iter.hasNext();) {
364
                        Variable variable = (Variable) iter.next();        
365
                        if (!gridMathPanel.getGridMath().getParams().containsKey(variable.getName())){
366
                                        RasterToolsUtil.messageBoxError(PluginServices.getText(this,"variables_sin_asignar"),this);
367
                                        return;
368
                                }
369
                }
370
                params= gridMathPanel.getGridMath().getParams();
371
                loadEnd= true;
372
        }
373
        
374
        
375
        public int getPercent(){
376
                
377
                /*if(!loadEnd)
378
                        return (int)((loadBuffers-1)/numVar)*100;
379
                else */if(writerBufferServer!=null)
380
                        return writerBufferServer.getPercent();
381
                else
382
                        return percent;
383
        }
384
        
385
        
386
        /*
387
         * (non-Javadoc)
388
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLog()
389
         */
390
        public String getLog() {
391
                
392
/*                if(!loadEnd)
393
                        return PluginServices.getText(this,"cargando datos")+"...";*/
394
                /*else*/ if (writerBufferServer!=null)
395
                        return PluginServices.getText(this,"escribiendo_resultado")+"...";
396
                else
397
                        return PluginServices.getText(this,"calculando_imagen")+"...";
398
        }
399

    
400

    
401
        public Object getResult(){
402
                return rasterResult;
403
        }
404
}