Revision 9898

View differences:

org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.principalcomponents.algorithm.PrincipalComponentsAlgorithmLibrary
0 2

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/resources/org/gvsig/raster/principalcomponents/algorithm/i18n/text.properties
1
layers_dont_intersect=Las capas no intersectan
2
roi_not_inside=La zona de estudio no esta contenida en la extensi?n de las capas
3
calc_stats="Calculando estad?sticas para PCA"
4
error_covarianza_optimize="Error en el covarianceOptimize() : C?lculo de la matriz varianza covarianza de las bandas de un Grid."
5
preparing_buffers=Preparando buffers
6
writting_in_buffer=Escribiendo en buffer de salida
7
processing_pc=Procesando Componentes Principales
8
principal_components=Componentes Principales
0 9

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/resources/org/gvsig/raster/principalcomponents/algorithm/i18n/text_en.properties
1
layers_dont_intersect=Layers do not intersect
2
roi_not_inside=The region of interest are not inside the extension of the layers
3
calc_stats="Calculating statistics to PCA"
4
error_covarianza_optimize="Error in covarianceOptimize."
5
preparing_buffers=Preparing buffers
6
writting_in_buffer=Writing in the output buffer
7
processing_pc=Processing Principal Components
8
principal_components=Principal Components
0 9

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PrincipalComponentsException.java
1
package org.gvsig.raster.principalcomponents.algorithm;
2

  
3
import org.gvsig.raster.algorithm.process.ProcessException;
4

  
5

  
6
/**
7
 * This exception is thrown if happen problems processing data with this algorithm.
8
 */
9
public class PrincipalComponentsException extends ProcessException {
10
	private static final long serialVersionUID = -3022090543908771484L;
11
	
12
	public PrincipalComponentsException(String msg){
13
		super(msg);
14
	}
15
	
16
	public PrincipalComponentsException(String msg, Throwable e){
17
		super(msg, e);
18
	}
19
}
0 20

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PrincipalComponentsProcess.java
1
package org.gvsig.raster.principalcomponents.algorithm;
2

  
3
import java.awt.geom.Rectangle2D;
4
import java.util.List;
5

  
6
import org.gvsig.fmap.dal.coverage.RasterLocator;
7
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
8
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
9
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
10
import org.gvsig.fmap.dal.coverage.exception.CloneException;
11
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
12
import org.gvsig.fmap.dal.coverage.exception.ROIException;
13
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
14
import org.gvsig.i18n.Messages;
15
import org.gvsig.raster.algorithm.process.DataProcess;
16
import org.gvsig.raster.algorithm.process.ProcessException;
17
import org.gvsig.raster.roi.ROI;
18

  
19
import Jama.Matrix;
20

  
21
/**
22
 * PCA Process 
23
 * @author Nacho Brodin (nachobrodin@gmail.com)
24
 */
25
public class PrincipalComponentsProcess extends DataProcess {
26
	public static String          RASTER_STORE       = "RASTER_STORE";
27
	public static String          PATH               = "PATH";
28
	public static String          FILENAME           = "FILENAME";
29
	
30
	public static final String    BUFFERS            = "BUFFERS";
31
	public static final String    SELECTEDPCS        = "SELECTEDPCS";
32
	public static final String    PCSTATISTICS       = "PCSTATISTICS";
33
	public static final String    GRAPHIC_DATA       = "GRAPHIC_DATA";
34
	public static final String    BANDS              = "BANDS";
35
	
36
	private RasterDataStore       store              = null;
37
	private String                filename           = null;
38
	
39
	private PCStatsDataStructure  pcStatistics       = null;
40
	private List<ROI>             rois               = null;
41
	private Extent                extentResult       = null;
42
	private boolean[]             selectedPCs        = null;
43
	private boolean[]             bands              = null;
44
	private int[]                 selectedBands      = null;
45
	private NoData                nodata             = null;
46
	
47
	
48
	public static void registerParameters() {
49
		registerInputParameter(RASTER_STORE, RasterDataStore.class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
50
		registerInputParameter(PCSTATISTICS, PCStatsDataStructure.class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
51
		registerInputParameter(PATH, String.class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
52
		registerInputParameter(SELECTEDPCS, Boolean[].class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
53
		registerInputParameter(BANDS, Boolean[].class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
54
		
55
		registerOutputParameter(FILENAME, String.class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
56
		registerOutputParameter(GRAPHIC_DATA, Double[].class, PrincipalComponentsAlgorithmLibrary.PC_PROCESS_LABEL);
57
	}
58
	
59
	public void init() {
60
		store = getParam(RASTER_STORE) != null ? (RasterDataStore)getParam(RASTER_STORE) : null;
61
		filename = getStringParam(PATH);
62
		selectedPCs = (boolean[]) getParam(SELECTEDPCS);
63
		bands = (boolean[]) getParam(BANDS);
64
		pcStatistics = (PCStatsDataStructure) getParam(PCSTATISTICS);
65
	}
66

  
67
	public void process() throws ProcessInterruptedException, ProcessException {
68
		insertLineLog(Messages.getText("processing_pc"));
69
		try {
70
			if (store == null)
71
				throw new PrincipalComponentsException(Messages.getText("need_a_input"));
72
			
73
			if(getROIEPSG() != null) {
74
				try {
75
					rois = store.getRois(getROIEPSG());
76
				} catch (ROIException e2) {
77
					logger.error(Messages.getText("error_getting_rois"), e2);
78
				}
79
			}
80
			
81
			try {
82
				store = ((RasterDataStore)store).cloneDataStore();
83
			} catch (CloneException e) {
84
				new PrincipalComponentsException("Error cloning the input DataStore", e);
85
			}
86
			
87
			extentResult = getExtentResult(getOutputWindow(), rois, store);
88
			Rectangle2D sourcePxBBox = getSourcePxBox(extentResult, store);
89
			
90
			double cellSize = store.getCellSize();
91
			
92
			nodata = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(1, Buffer.TYPE_DOUBLE);
93
			double nodataValue = nodata.getValue().doubleValue();
94
			
95
			int numberOfOutputBands = getNumberOfOutputBands(selectedPCs);
96
			
97
			Buffer outputBuffer = createOutputBuffer((int)sourcePxBBox.getWidth(), (int)sourcePxBBox.getHeight(), numberOfOutputBands);
98
			Buffer sourceBuffer = createSourceBuffer(store, sourcePxBBox, bands);
99
			
100
			// Matriz Autovectores
101
			// Colocamos la matriz en el orden correcto:
102
			/*
103
			 * b3 b2 b1 c1 c2 c3 | | | | Cambio de orden de columnas de la matriz
104
			 * transpuesta ___ \ / V c1 c2 c3 b1 b2 b3
105
			 */
106
			Matrix autovect = changeColumns((pcStatistics.getAutoVectorsMatrix().transpose()));
107
			insertLineLog(Messages.getText("writting_in_buffer"));
108
			
109
			for (int i = 0; i < sourceBuffer.getHeight(); i++) {
110
				for (int j = 0; j < sourceBuffer.getWidth(); j++) {
111

  
112
					if (isInsideOfROI(j, i, rois, extentResult)) {
113
						for (int iComponent = 0; iComponent < sourceBuffer.getBandCount(); iComponent++) {
114
							if(selectedPCs[iComponent]) {
115
								double valor = 0;
116
								for (int iBand = 0; iBand < sourceBuffer.getBandCount(); iBand++) {
117
									valor += getData(sourceBuffer, i, j, iBand) * autovect.get(iBand, iComponent);
118
								}
119
								int indexBandResult = indexBandResult(selectedPCs, iComponent);
120
								outputBuffer.setElem(i, j, indexBandResult, (double) valor);
121
							}
122
						}
123
						
124
					} else {
125
						for (int iBand = 0; iBand < outputBuffer.getBandCount(); iBand++) {
126
							outputBuffer.setElem(i, j, iBand, nodataValue);
127
						}
128
					}
129
				}
130
				updatePercent((int)(i * 100 / sourcePxBBox.getHeight()), 100);
131
			}
132
			
133
            super.exportRaster(filename, outputBuffer, cellSize, extentResult.getULX(),
134
                extentResult.getULY(), nodata, store.getProjection());
135
			
136
			addOutputValue(FILENAME, filename);
137
			addOutputValue(GRAPHIC_DATA, filename);
138
		} catch (PrincipalComponentsException e) {
139
			if (incrementableTask != null)
140
				incrementableTask.processFinalize();
141
			messageBoxError("principal_components", null, e);
142
		}
143
	}
144
	
145
	
146
	/**
147
	 * Gets the number of the selected bands
148
	 * @param bandsPCs
149
	 * @return
150
	 */
151
	private int getNumberOfOutputBands(boolean[] b) {
152
		int bandCount = 0;
153
        for (int i = 0; i < b.length; i++) {
154
			if(b[i])
155
				bandCount++;
156
		}
157
        return bandCount;
158
	}
159
	
160
	/**
161
	 * Gets the band index of the result buffer 
162
	 * @param bandsPCs
163
	 * @param indexIn
164
	 * @return
165
	 */
166
	private int indexBandResult(boolean[] bandsPCs, int indexIn) {
167
		if(selectedBands == null) {
168
			selectedBands = new int[bandsPCs.length];
169
			int indexOut = 0;
170
			for (int i = 0; i < bandsPCs.length; i++) {
171
				if(bandsPCs[i]) {
172
					selectedBands[i] = indexOut;
173
					indexOut++;
174
				} else
175
					selectedBands[i] = -1;
176
			}
177
		}
178
		return selectedBands[indexIn];
179
	}
180
	
181
	public double getScaleFactor(Buffer buffer, int sizePreview) {
182
		double x = 0, y = 0;
183
		x = 200.0 / buffer.getWidth();
184
		y = 200.0 / buffer.getHeight();
185

  
186
		if (x > y) {
187
			return y;
188
		} else {
189
			return x;
190
		}
191
	}
192
	
193
	private Matrix changeColumns(Matrix m) {
194
		Matrix result = new Matrix(m.getRowDimension(), m.getColumnDimension());
195
		int k = m.getColumnDimension() - 1;
196
		for (int i = 0; i < m.getRowDimension(); i++) {
197
			for (int j = 0; j < m.getColumnDimension(); j++) {
198
				result.set(i, j, m.get(k - i, j));
199
			}
200
		}
201
		return result;
202
	}
203
	
204
	public String getTitle() {
205
		return Messages.getText("...");
206
	}
207
}
0 208

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PCStatsDataStructure.java
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

  
23
package org.gvsig.raster.principalcomponents.algorithm;
24

  
25
import Jama.Matrix;
26

  
27
/**
28
 * Represents statistics needed to generate a transformated raster by PCA method
29
 * @author seriznue
30
 */
31
public class PCStatsDataStructure {
32
	
33
	private Matrix 			autoVectorsMatrix 	= null;
34
	private Matrix 			coVarMatrix 		= null;
35
	private double			autovalues[]		= null;
36
	private double[][]      maxminmean			= null;
37
	
38
	/**
39
	 * Constructor.
40
	 * 
41
	 * @param autoVectorsMatrix Matrix of autovectors.
42
	 * @param autovalues Array of eigenvalues.
43
	 * @param coVarMatrix Matrix of Covariance.
44
	 */
45
	public PCStatsDataStructure(Matrix autoVectorsMatrix, double[] autovalues, Matrix coVarMatrix) {
46
		this.autoVectorsMatrix = autoVectorsMatrix;
47
		this.autovalues = autovalues;
48
		this.coVarMatrix = coVarMatrix;
49
	}
50

  
51

  
52
	public Matrix getAutoVectorsMatrix() {
53
		return autoVectorsMatrix;
54
	}
55

  
56

  
57
	public void setAutoVectorsMatrix(Matrix autoVectorsMatrix) {
58
		this.autoVectorsMatrix = autoVectorsMatrix;
59
	}
60
	
61
	public double[][] getMaxMinMean() {
62
		return maxminmean;
63
	}
64

  
65
	public void setMaxMinMean(double[][] maxminmean) {
66
		this.maxminmean = maxminmean;
67
	}
68

  
69

  
70
	public Matrix getCoVarMatrix() {
71
		return coVarMatrix;
72
	}
73

  
74

  
75
	public void setCoVarMatrix(Matrix coVarMatrix) {
76
		this.coVarMatrix = coVarMatrix;
77
	}
78

  
79

  
80
	public double[] getAutovalues() {
81
		return autovalues;
82
	}
83

  
84

  
85
	public void setAutovalors(double[] autovalors) {
86
		this.autovalues = autovalors;
87
	}
88
	
89
}
0 90

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PCAStatisticsProcess.java
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.principalcomponents.algorithm;
23

  
24

  
25
import java.awt.geom.Rectangle2D;
26
import java.util.List;
27

  
28
import org.cresques.Messages;
29
import org.gvsig.fmap.dal.coverage.RasterLocator;
30
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
31
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
32
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
33
import org.gvsig.fmap.dal.coverage.exception.CloneException;
34
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
35
import org.gvsig.fmap.dal.coverage.exception.ROIException;
36
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
37
import org.gvsig.fmap.dal.exception.CloseException;
38
import org.gvsig.raster.algorithm.process.DataProcess;
39
import org.gvsig.raster.algorithm.process.ProcessException;
40
import org.gvsig.raster.roi.ROI;
41
import org.slf4j.Logger;
42
import org.slf4j.LoggerFactory;
43

  
44
import Jama.EigenvalueDecomposition;
45
import Jama.Matrix;
46

  
47
/**
48
 * This Process computes a <code>PCStatsDataStructure</code> Object from bands of two images in a study zone.
49
 * <code>PCStatsDataStructure</code> is a object that contains the needed statistics to Principal Components decomposition
50
 * of images.
51
 * 
52
 * @author Nacho Brodin (nachobrodin@gmail.com)
53
 * 
54
 */
55
public class PCAStatisticsProcess extends DataProcess {
56
    public static final String 	 LAYER_ZONA_ESTUDIO 			= "LAYER_ZONA_ESTUDIO";
57
    public static String         BANDS 							= "BANDS";
58
    public static String         PATH 							= "PATH";
59
    public static String         ROI_EPSG                       = "ROI_EPSG";
60
    public static String         WINDOW                         = "WINDOW";
61
    
62
	public static String         RASTER_STORE                   = "RASTER_STORE";
63
	public static String         STATS_RESULT                   = "STATS_RESULT";
64
	
65
    private boolean[] 			 bands 							= null;
66
    private RasterDataStore      store 							= null;
67
    private Buffer               buffer 						= null;
68
    private Buffer               roiBuffer 						= null;
69
    private boolean              roiBufferCalculated            = false;
70
	private double				 autovalors[]					= null;
71
	private Matrix 				 coVarMatrix					= null;
72
	private Matrix 				 autoVectorMatrix				= null;
73
	private double 				 coVar[][] 						= null;
74
	private static Logger 		 logger    		   				= LoggerFactory.getLogger(PCAStatisticsProcess.class.getName());
75
    private double[][] 			 maxminmean						= null;
76
    private	Extent 				 extentResult					= null; 
77
    private String               path                           = null;
78
    private List<ROI>            rois                           = null;
79
    
80
    private boolean[]            statsByBandCalculated          = null;
81
	 
82
	public static void registerParameters() {
83
		registerInputParameter(RASTER_STORE, RasterDataStore.class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
84
		registerInputParameter(BANDS, Boolean[].class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
85
		registerInputParameter(PATH, String.class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
86
		
87
		registerOutputParameter(STATS_RESULT, PCStatsDataStructure.class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
88
		registerOutputParameter(PATH, String.class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
89
		registerOutputParameter(BANDS, Boolean[].class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
90
		registerOutputParameter(ROI_EPSG, String.class, PrincipalComponentsAlgorithmLibrary.PC_STATS_PROCESS_LABEL);
91
	}
92
	
93
	@Override
94
	public void init() {
95
		store = (RasterDataStore)getParam(RASTER_STORE);
96
		bands = (boolean[])getParam(BANDS);
97
		path = getStringParam(PATH);
98
	}
99
	
100
	public double[] getAutoValors() {
101
		return  autovalors;
102
	}
103
	
104
	/**
105
	 * @return Autovectors Matrix
106
	 */
107
	public Matrix getAutoVectorMatrix() {
108
		return autoVectorMatrix;
109
	}
110
	
111
	/**
112
	 * @return Varianze-covarianze Matrix
113
	 */
114
	public Matrix getcoVarMatrix() {
115
		return coVarMatrix;
116
	}
117
	
118
	public boolean isInsideOfROI(int x, int y, List<ROI> rois, Extent extentResult) {
119
		if(roiBufferCalculated)
120
			return (roiBuffer.getElemByte(y, x, 0) == 1);
121
		if(roiBuffer == null)
122
			roiBuffer = createOutputBuffer(buffer.getWidth(), buffer.getHeight(), 1, Buffer.TYPE_BYTE);
123
		boolean a = super.isInsideOfROI(x, y, rois, extentResult);
124
		roiBuffer.setElem(y, x, 0, a ? (byte)1: (byte)0);
125
		return a;
126
	}
127
	
128
	/**
129
	 * Calculate the Varianze-covarianze Matrix from bands of a Grid
130
	 * @throws InterruptedException 
131
	 * @throws ProcessInterruptedException 
132
	 */
133
	private double[][] covarianceOptimize() throws InterruptedException, ProcessInterruptedException {
134
        //NoData
135
        NoData nd = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(1, Buffer.TYPE_DOUBLE);
136
        
137
        double nodata = nd.getValue().doubleValue();
138
		double dSum = 0;
139
		int iValues = 0;
140
		double[][] coV = new double[buffer.getBandCount()][buffer.getBandCount()];
141
		
142
		double valorBandai = 0, valorBandaj = 0;
143
		maxminmean = new double[buffer.getBandCount()][4];
144
		statsByBandCalculated = new boolean[buffer.getBandCount()];
145
		for (int i = 0; i < statsByBandCalculated.length; i++) {
146
			statsByBandCalculated[i] = false;
147
		}
148
		
149
		loadDataStoreStatistics();
150
		
151
		int percent = 0;
152
		int maxCounter = 0;
153
		for (int i = buffer.getBandCount(); i >= 0; i--) {
154
			maxCounter += i;
155
		}
156
		
157
		for (int i = 0; i < buffer.getBandCount(); i++) {
158
			double meanBufferToOperatei = getMeanValue(i, buffer);
159
			for (int j = i; j < buffer.getBandCount(); j++) {
160
				iValues = 0;
161
				dSum = 0;
162
				double meanBufferToOperatej = getMeanValue(j, buffer);
163

  
164
				for (int row = 0; row < buffer.getHeight(); row++) {
165
					for (int col = 0; col < buffer.getWidth(); col++) {
166
						if(isInsideOfROI(col, row, rois, extentResult)) {
167
							valorBandai = getData(buffer, row, col, i) - meanBufferToOperatei;
168
							valorBandaj = getData(buffer, row, col, j) - meanBufferToOperatej;
169

  
170
							dSum += valorBandai * valorBandaj;
171
							iValues++;
172
						}
173
					}
174
					updatePercent(percent, maxCounter);
175
				}
176
				roiBufferCalculated = true;
177
				
178
				// Asigno el valor a la matriz 
179
				if (iValues > 1)
180
					coV[i][j] = dSum / (double)(iValues);	
181
				else
182
					coV[i][j] = nodata;
183
				
184
				percent ++;
185
				updatePercent(percent, maxCounter);
186
			}
187

  
188
		}
189
		
190
		for (int i = 0; i < buffer.getBandCount(); i++) {
191
			for (int j = 0; j < buffer.getBandCount(); j++) {
192
				if(j < i)
193
					coV[i][j] = coV[j][i];
194
			}
195
		}
196

  
197
		return coV;
198
	}
199
	
200
//	 * Devuelve la media de los valores de los pixeles de un buffer incluidos en la zona de estudio
201
	/**
202
	 * Get the mean of values of pixels from a buffer in a study zone
203
	 * @param bufferToOperate
204
	 * @return
205
	 */
206
	private double getMeanValue(int band, Buffer bufferToOperate) {
207
		if(statsByBandCalculated[band])
208
			return maxminmean[band][2];
209
		
210
		double mean = 0;
211
		double variance = 0;
212
		double min = Double.MAX_VALUE;
213
		double max = Double.MIN_VALUE;
214
		int valuesCounter = 0;
215
		for (int j = 0; j < bufferToOperate.getHeight(); j++) {
216
			for (int i = 0; i < bufferToOperate.getWidth(); i++) {
217
				if (isInsideOfROI(i, j, rois, extentResult)) {
218
					double value = getData(bufferToOperate, j, i, band);
219
					
220
					if(value < min) {
221
						min = value;
222
					}
223

  
224
					if(value > max) {
225
						max = value;
226
					}
227
					
228
					mean += value;
229
					variance += value * value;
230
					valuesCounter++;
231
				}
232
			}
233

  
234
		}
235
		roiBufferCalculated = true;
236
		mean = (mean / valuesCounter);
237
		variance = variance / (double) valuesCounter - mean * mean;
238
		maxminmean[band][0] = max;
239
		maxminmean[band][1] = min;
240
		maxminmean[band][2] = mean;
241
		maxminmean[band][3] = variance;
242
		statsByBandCalculated[band] = true;
243
		return mean;
244
	}
245
	
246
	private void loadDataStoreStatistics() {
247
		if(isAnalizedEntireLayer(getOutputWindow(), rois, store) && store.getStatistics().isCalculated()) {
248
			double[] max = store.getStatistics().getMax();
249
			double[] min = store.getStatistics().getMin();
250
			double[] mean = store.getStatistics().getMean();
251
			double[] variance = store.getStatistics().getVariance();
252
			int iBand = 0;
253
			for (int i = 0; i < mean.length; i++) {
254
				if(bands[i]) {
255
					maxminmean[iBand][0] = max[i];
256
					maxminmean[iBand][1] = min[i];
257
					maxminmean[iBand][2] = mean[i];
258
					maxminmean[iBand][3] = variance[i];
259
					statsByBandCalculated[iBand] = true;
260
					iBand ++;
261
				}
262
			}
263
		}
264
	}
265

  
266
	@Override
267
	public void process() throws ProcessInterruptedException, ProcessException {
268
		insertLineLog(Messages.getText("preparing_buffers"));
269

  
270
		if(getROIEPSG() != null) {
271
			try {
272
				rois = store.getRois(getROIEPSG());
273
			} catch (ROIException e2) {
274
				logger.error(Messages.getText("error_getting_rois"), e2);
275
			}
276
		}
277
			
278
		try {
279
			store = store.cloneDataStore();
280
		} catch (CloneException e1) {
281
			throw new ProcessException("Error cloning the sources", e1);
282
		}
283
			
284
		//Calculo de datos de entrada
285
		extentResult = getExtentResult(getOutputWindow(), rois, store);
286
		Rectangle2D sourcePxBBox = getSourcePxBox(extentResult, store);
287

  
288
		buffer = createSourceBuffer(store, sourcePxBBox, bands);
289

  
290
		insertLineLog(Messages.getText("calc_stats"));
291

  
292
		try {
293
			coVar = covarianceOptimize();
294
		} catch (InterruptedException e) {
295
			logger.error(Messages.getText("error_covarianza_optimize"), e);
296
		}
297
		// Calculo de autovectores:
298
		coVarMatrix = new Matrix(coVar);
299
		EigenvalueDecomposition eigenvalueDecomp = new EigenvalueDecomposition(coVarMatrix); 
300
		//Autovectores
301
		autoVectorMatrix = eigenvalueDecomp.getV();
302

  
303
		// Autovalores
304
		autovalors = eigenvalueDecomp.getRealEigenvalues();	
305

  
306
		PCStatsDataStructure resultStatistics = new PCStatsDataStructure(autoVectorMatrix, autovalors, coVarMatrix);
307
		resultStatistics.setMaxMinMean(maxminmean);
308
		
309
		roiBuffer.dispose();
310
		//Object[] dataROI = new Object[]{vectROI, (int)shift[0].getX(), (int)shift[0].getY()};	
311
		addOutputValue(STATS_RESULT, resultStatistics);
312
		addOutputValue(PATH, path);
313
		addOutputValue(BANDS, bands);
314
		addOutputValue(ROI_EPSG, getROIEPSG());
315
		try {
316
			store.close();
317
		} catch (CloseException e) {
318
			throw new ProcessException("Error closing the sources", e);
319
		}
320
	}
321
 
322

  
323
	public String getTitle() {
324
		return null;
325
	}
326
}
0 327

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PCStatistics.java
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

  
23
package org.gvsig.raster.principalcomponents.algorithm;
24

  
25
import Jama.Matrix;
26

  
27
/**
28
 * Represents statistics needed to generate a transformated raster by PCA method
29
 * @author seriznue
30
 */
31
public class PCStatistics {
32
	
33
	private Matrix 			autoVectorsMatrix 	= null;
34
	private Matrix 			coVarMatrix 		= null;
35
	private double			autovalues[]		= null;
36
	
37
	/**
38
	 * Constructor.
39
	 * 
40
	 * @param autoVectorsMatrix Matrix of autovectors.
41
	 * @param autovalues Array of eigenvalues.
42
	 * @param coVarMatrix Matrix of Covariance.
43
	 */
44
	public PCStatistics(Matrix autoVectorsMatrix, double[] autovalues, Matrix coVarMatrix) {
45
		this.autoVectorsMatrix = autoVectorsMatrix;
46
		this.autovalues = autovalues;
47
		this.coVarMatrix = coVarMatrix;
48
	}
49

  
50

  
51
	public Matrix getAutoVectorsMatrix() {
52
		return autoVectorsMatrix;
53
	}
54

  
55

  
56
	public void setAutoVectorsMatrix(Matrix autoVectorsMatrix) {
57
		this.autoVectorsMatrix = autoVectorsMatrix;
58
	}
59

  
60

  
61
	public Matrix getCoVarMatrix() {
62
		return coVarMatrix;
63
	}
64

  
65

  
66
	public void setCoVarMatrix(Matrix coVarMatrix) {
67
		this.coVarMatrix = coVarMatrix;
68
	}
69

  
70

  
71
	public double[] getAutovalues() {
72
		return autovalues;
73
	}
74

  
75

  
76
	public void setAutovalors(double[] autovalors) {
77
		this.autovalues = autovalors;
78
	}
79
	
80
}
0 81

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/java/org/gvsig/raster/principalcomponents/algorithm/PrincipalComponentsAlgorithmLibrary.java
1
package org.gvsig.raster.principalcomponents.algorithm;
2

  
3
import org.gvsig.i18n.Messages;
4
import org.gvsig.raster.algorithm.RasterBaseAlgorithmLibrary;
5
import org.gvsig.tools.library.AbstractLibrary;
6
import org.gvsig.tools.library.LibraryException;
7

  
8
/**
9
 * Initialization of PrincipalComponentsAlgorithmLibrary library.
10
 */
11
public class PrincipalComponentsAlgorithmLibrary extends AbstractLibrary {
12
	public static final String         PC_PROCESS_LABEL         = "PrincipalComponentsProcess";
13
	public static final String         PC_STATS_PROCESS_LABEL   = "StatsPrincipalComponentsProcess";
14
	
15
    @Override
16
    protected void doInitialize() throws LibraryException {
17
        // Nothing to do
18
    }
19

  
20
    @Override
21
    protected void doPostInitialize() throws LibraryException {
22
    	//Registers the process and its parameters
23
    	RasterBaseAlgorithmLibrary.register(PC_STATS_PROCESS_LABEL, PCAStatisticsProcess.class);
24
    	PCAStatisticsProcess.registerParameters();
25
    	RasterBaseAlgorithmLibrary.register(PC_PROCESS_LABEL, PrincipalComponentsProcess.class);
26
    	PrincipalComponentsProcess.registerParameters();
27
    	
28
        Messages.addResourceFamily(
29
            "org.gvsig.raster.principalcomponents.algorithm", 
30
            PrincipalComponentsAlgorithmLibrary.class.getClassLoader(), 
31
            PrincipalComponentsAlgorithmLibrary.class.getClass().getName());
32
        //registerGeoProcess(new RasterReprojectAlgorithmLibrary());
33
        
34
        Messages.addResourceFamily("org.gvsig.raster.principalcomponents.algorithm.i18n.text",
35
        		PrincipalComponentsAlgorithmLibrary.class.getClassLoader(),
36
        		PrincipalComponentsAlgorithmLibrary.class.getClass().getName()); 
37
    }
38
}
0 39

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/resources-plugin/org/gvsig/raster/principalcomponents/algorithm/i18n/text_en.properties
1
layers_dont_intersect=Layers do not intersect
2
roi_not_inside=The region of interest are not inside the extension of the layers
3
calc_stats="Calculating statistics to PCA"
4
error_covarianza_optimize="Error in covarianceOptimize."
5
preparing_buffers=Preparing buffers
0 6

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/src/main/resources-plugin/org/gvsig/raster/principalcomponents/algorithm/i18n/text.properties
1
layers_dont_intersect=Las capas no intersectan
2
roi_not_inside=La zona de estudio no esta contenida en la extensi?n de las capas
3
calc_stats="Calculando estad?sticas para PCA"
4
error_covarianza_optimize="Error en el covarianceOptimize() : C?lculo de la matriz varianza covarianza de las bandas de un Grid."
5
preparing_buffers=Preparando buffers
0 6

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.algorithm/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<modelVersion>4.0.0</modelVersion>
4
	<artifactId>org.gvsig.raster.principalcomponents.algorithm</artifactId>
5
	<packaging>jar</packaging>
6
	<name>org.gvsig.raster.principalcomponents.algorithm</name>
7
	<parent>
8
		<groupId>org.gvsig</groupId>
9
		<artifactId>org.gvsig.raster.principalcomponents</artifactId>
10
		<version>2.2.83</version>
11
	</parent>
12
    <dependencies>
13
		<dependency>
14
			<groupId>org.gvsig</groupId>
15
			<artifactId>org.gvsig.raster.algorithm</artifactId>
16
            <scope>compile</scope>
17
		</dependency>
18
		<dependency>
19
            <groupId>org.gvsig</groupId>
20
            <artifactId>org.gvsig.i18n</artifactId>
21
            <scope>compile</scope>
22
        </dependency>
23
        <dependency>
24
            <groupId>org.gvsig</groupId>
25
            <artifactId>org.gvsig.tools.lib</artifactId>
26
            <scope>compile</scope>
27
        </dependency>
28
        <dependency>
29
            <groupId>org.gvsig</groupId>
30
            <artifactId>org.gvsig.ui</artifactId>
31
            <scope>compile</scope>
32
        </dependency>
33
        		<dependency>
34
			<groupId>org.gvsig</groupId>
35
			<artifactId>org.gvsig.raster.lib.api</artifactId>
36
            <scope>compile</scope>
37
		</dependency>
38
        <dependency>
39
            <groupId>org.gvsig</groupId>
40
            <artifactId>org.gvsig.raster.lib.impl</artifactId>
41
            <scope>compile</scope>
42
        </dependency>
43
        <dependency>
44
            <groupId>org.gvsig</groupId>
45
            <artifactId>org.gvsig.raster.fmap</artifactId>
46
            <scope>compile</scope>
47
        </dependency>
48
        <dependency>
49
            <groupId>org.gvsig</groupId>
50
            <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
51
            <scope>compile</scope>
52
        </dependency>
53
        
54
        <dependency>
55
            <groupId>org.gvsig</groupId>
56
            <artifactId>org.gvsig.fmap.geometry.api</artifactId>
57
            <scope>compile</scope>
58
        </dependency>
59
    <!--
60
        <dependency>
61
            <groupId>org.gvsig</groupId>
62
            <artifactId>org.gvsig.fmap.geometry.generalpath</artifactId>
63
            <scope>runtime</scope>
64
        </dependency>
65
    -->
66
        <dependency>
67
            <groupId>org.gvsig</groupId>
68
            <artifactId>org.gvsig.compat.api</artifactId>
69
            <scope>compile</scope>
70
        </dependency>
71
        <dependency>
72
            <groupId>org.gvsig</groupId>
73
            <artifactId>org.gvsig.compat.se</artifactId>
74
            <scope>compile</scope>
75
        </dependency>
76
        <dependency>
77
            <groupId>org.gvsig</groupId>
78
            <artifactId>org.gvsig.projection.api</artifactId>
79
            <scope>compile</scope>
80
        </dependency>
81
        <dependency>
82
            <groupId>org.gvsig</groupId>
83
            <artifactId>org.gvsig.projection.cresques.impl</artifactId>
84
            <scope>runtime</scope>
85
        </dependency>
86
        <dependency>
87
            <groupId>org.gvsig</groupId>
88
            <artifactId>org.gvsig.fmap.dal.api</artifactId>
89
            <scope>compile</scope>
90
        </dependency>
91
        <dependency>
92
            <groupId>org.gvsig</groupId>
93
            <artifactId>org.gvsig.fmap.dal.impl</artifactId>
94
            <scope>compile</scope>
95
        </dependency>
96
        <dependency>
97
            <groupId>org.gvsig</groupId>
98
            <artifactId>org.gvsig.fmap.dal.file.lib</artifactId>
99
            <scope>compile</scope>
100
        </dependency>
101
        <dependency>
102
            <groupId>org.gvsig</groupId>
103
            <artifactId>org.gvsig.fmap.dal.spi</artifactId>
104
            <scope>compile</scope>
105
        </dependency>
106
        <dependency>
107
			<groupId>org.gvsig.legacy</groupId>
108
			<artifactId>jama</artifactId>
109
			<scope>compile</scope>
110
		</dependency>
111
	</dependencies>
112
</project>
0 113

  
org.gvsig.raster.principalcomponents/tags/org.gvsig.raster.principalcomponents-2.2.83/org.gvsig.raster.principalcomponents.swing/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3

  
4
	<modelVersion>4.0.0</modelVersion>
5
	<artifactId>org.gvsig.raster.principalcomponents.swing</artifactId>
6
	<packaging>pom</packaging>
7
	<name>org.gvsig.raster.principalcomponents.swing</name>
8
	<parent>
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff