Statistics
| Revision:

gvsig-geoprocess / org.gvsig.geoprocess / trunk / org.gvsig.geoprocess / org.gvsig.geoprocess.algorithm / org.gvsig.geoprocess.algorithm.spatialjoin / src / main / java / org / gvsig / geoprocess / algorithm / spatialjoin / SpatialJoinAlgorithm.java @ 245

History | View | Annotate | Download (10.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2012 gvSIG Association.
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
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.geoprocess.algorithm.spatialjoin;
25

    
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.Iterator;
29

    
30
import es.unex.sextante.core.Sextante;
31
import es.unex.sextante.dataObjects.IVectorLayer;
32
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
33
import es.unex.sextante.exceptions.RepeatedParameterNameException;
34
import es.unex.sextante.exceptions.UnsupportedOutputChannelException;
35
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
36
import es.unex.sextante.outputs.OutputVectorLayer;
37

    
38
import org.gvsig.fmap.dal.DALLocator;
39
import org.gvsig.fmap.dal.DataManager;
40
import org.gvsig.fmap.dal.DataTypes;
41
import org.gvsig.fmap.dal.exception.DataException;
42
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
43
import org.gvsig.fmap.dal.feature.FeatureSet;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.dal.feature.FeatureType;
46
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
47
import org.gvsig.geoprocess.algorithm.dissolve.DissolveRule;
48
import org.gvsig.geoprocess.algorithm.dissolve.IDissolveRule;
49
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
50
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
51
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
52

    
53
/**
54
 * Spatial join algorithm
55
 * @author <a href="mailto:nachobrodin@gmail.com">Nacho Brodin</a>
56
 */
57
public class SpatialJoinAlgorithm extends AbstractSextanteGeoProcess {
58

    
59
        public static final String        NEW_FIELD         = "NUM_RELA";
60
        public static final String        RESULT            = "RESULT";
61
        public static final String        LAYER1            = "LAYER1";
62
        public static final String        LAYER2            = "LAYER2";
63
        public static final String        SELECTED_GEOM     = "SELECTED_GEOM";
64
        public static final String        NEAREST           = "NEAREST";
65
        public static final String        FUNCTION_LIST     = "FUNCTION_LIST";
66
        public static final String        Summary[]         = {"Min", "Max", "Sum", "Avg"};
67
        private boolean                   funcList[]        = new boolean[Summary.length];
68
        private HashMap<String, String>   funcMap           = new HashMap<String, String>();
69
        
70
        /*
71
         * (non-Javadoc)
72
         * @see es.unex.sextante.core.GeoAlgorithm#defineCharacteristics()
73
         */
74
        public void defineCharacteristics(){
75
        setName(getTranslation("Spatialjoin"));
76
        setGroup(getTranslation("basic_vect_algorithms"));
77
        // setGeneratesUserDefinedRasterOutput(false);
78
                
79
                try {
80
                        m_Parameters.addInputVectorLayer(LAYER1, 
81
                getTranslation("Input_layer"),
82
                                                                                                IVectorLayer.SHAPE_TYPE_WRONG, 
83
                                                                                                true);
84
                        m_Parameters.addInputVectorLayer(LAYER2, 
85
                getTranslation("Input_layer"),
86
                                                                                                IVectorLayer.SHAPE_TYPE_WRONG, 
87
                                                                                                true);
88
            m_Parameters.addBoolean(SELECTED_GEOM,
89
                getTranslation("Selected_geometries"), false);
90
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"),
91
                false);
92
            m_Parameters.addString(FUNCTION_LIST,
93
                getTranslation("Function_list"));
94
                } catch (RepeatedParameterNameException e) {
95
                        Sextante.addErrorToLog(e);
96
                }
97
                addOutputVectorLayer(RESULT,
98
 getTranslation("Spatialjoin"),
99
                                                                OutputVectorLayer.SHAPE_TYPE_UNDEFINED);
100
        }
101
        
102
        /*
103
         * (non-Javadoc)
104
         * @see es.unex.sextante.core.GeoAlgorithm#processAlgorithm()
105
         */
106
        public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
107
                IVectorLayer layer1 = m_Parameters.getParameterValueAsVectorLayer(LAYER1);
108
                IVectorLayer layer2 = m_Parameters.getParameterValueAsVectorLayer(LAYER2);
109
                boolean selectedGeom = m_Parameters.getParameterValueAsBoolean(SELECTED_GEOM);
110
                boolean nearest = m_Parameters.getParameterValueAsBoolean(NEAREST);
111
                String functionList = m_Parameters.getParameterValueAsString(FUNCTION_LIST);
112
                loadSummary(functionList);
113

    
114
                FlyrVectIVectorLayer lyr1 = null;
115
                FlyrVectIVectorLayer lyr2 = null;
116
                if(layer2 instanceof FlyrVectIVectorLayer && layer1 instanceof FlyrVectIVectorLayer) { 
117
                        lyr2 = ((FlyrVectIVectorLayer)layer2);
118
                        lyr1 = ((FlyrVectIVectorLayer)layer1);
119
                } else 
120
                        return false;
121

    
122
                DataManager dataManager = DALLocator.getDataManager();
123

    
124
                //Builds a new JSIRTree index. To do that we have to replace the default index and 
125
                //when the operation has finished then it restores the original default index 
126
                String indexName = "GEOMETRY";
127
                
128
                try {
129
                        indexName = lyr2.getFeatureStore().getDefaultFeatureType().getDefaultGeometryAttributeName();
130
                        FeatureAttributeDescriptor fat = lyr2.getFeatureStore().getDefaultFeatureType().getAttributeDescriptor(indexName);
131
                        String defaultIndex = dataManager
132
                                        .getDefaultFeatureIndexProviderName(fat.getDataType()
133
                                                        .getType());
134
                        dataManager.setDefaultFeatureIndexProviderName(fat.getDataType()
135
                                        .getType(), "JSIRTree");
136
                        lyr2.getFeatureStore().createIndex(lyr2.getFeatureStore().getDefaultFeatureType(), indexName, indexName + "_idx");
137
                        dataManager.setDefaultFeatureIndexProviderName(fat.getDataType()
138
                                        .getType(), defaultIndex);
139
                } catch (DataException e) {
140
                        Sextante.addErrorToLog(e);
141
                }
142

    
143
                //Builds the output and computes the operation
144
                try {
145
                        FeatureSet features = null;
146
                        features = lyr1.getFeatureStore().getFeatureSet();
147
                        FeatureType featureType1 = features.getDefaultFeatureType();
148
                        features = lyr2.getFeatureStore().getFeatureSet();
149
                        FeatureType featureType2 = features.getDefaultFeatureType();
150
                        
151
                        GeometryOperation operation = null;
152
                        FeatureStore outFeatStore = null;
153
                        
154
            if (nearest) {
155
                outFeatStore =
156
                    buildOutPutStoreFromUnion(featureType1, featureType2,
157
                        lyr1.getShapeType(), getTranslation("SpatialJoin"),
158
                        RESULT, "DIST", Double.class);
159

    
160
                operation =
161
                    new SpatiallyIndexedSpatialJoinOperation(lyr2, indexName
162
                        + "_idx");
163
            } else {
164
                outFeatStore =
165
                    buildSpatialJoinOutPutStore(featureType1,
166
                        lyr1.getShapeType(), getTranslation("SpatialJoin"),
167
                        RESULT);
168
                IDissolveRule rule = new DissolveRule(0, funcMap);
169
                Summary summary =
170
                    new Summary(rule, outFeatStore.getDefaultFeatureType());
171
                operation =
172
                    new IntersectsSpatialJoinOperation(lyr2,
173
                        indexName + "_idx", summary);
174
            }
175
                        
176
            operation.setTaskStatus(getStatus());
177
                        operation.computesGeometryOperation(lyr1.getFeatureStore(), 
178
                                        outFeatStore, 
179
                                        attrNames, 
180
                                        selectedGeom, 
181
                                        true);                
182
                } catch (DataException e) {
183
                        Sextante.addErrorToLog(e);
184
                }
185

    
186
                return true;
187
        }
188

    
189
        /**
190
         * Checks if the parameter is in Summary list
191
         * @param it
192
         * @return the position in the list
193
         */
194
        private int isInList(String it) {
195
                for (int i = 0; i < Summary.length; i++) {
196
                        if(Summary[i].compareTo(it) == 0)
197
                                return i;
198
                }
199
                return -1;
200
        }
201
        
202
        /**
203
         * Loads the list of functions to use
204
         * @param functionList
205
         */
206
        private void loadSummary(String functionList) {
207
                String[] attrList = functionList.split(";");
208
                for (int i = 0; i < attrList.length; i++) {
209
                        String[] func = attrList[i].split(",");
210
                        for (int j = 1; j < func.length; j++) {
211
                                int pos = isInList(func[j]);
212
                                if(pos != -1) {
213
                                        funcList[pos] = true;
214
                                        funcMap.put(Summary[pos], func[0]);
215
                                }
216
                        }
217
                }
218
        }
219
        
220
        /**
221
         * Builds the output FeatureStore 
222
         * @param featureType
223
         * @return FeatureStore
224
         */
225
        @SuppressWarnings("unchecked")
226
        protected FeatureStore buildSpatialJoinOutPutStore(FeatureType featureType1,
227
                                                                                        int shapeType,
228
                                                                                        String sextanteLayerName, 
229
                                                                                        String sextanteLayerLabel) {
230
                ArrayList<Class> typesList = new ArrayList<Class>();
231
                ArrayList<String> attr = new ArrayList<String>();
232
                
233
                Iterator it = featureType1.iterator();
234
                while( it.hasNext() ) {
235
                        FeatureAttributeDescriptor attribute = (FeatureAttributeDescriptor)it.next();
236
                        if (attribute.getDataType().getType() != DataTypes.GEOMETRY) {
237
                                attr.add(attribute.getName());
238
                                typesList.add(attribute.getObjectClass());
239
                        }
240
                }
241
                
242
                for (int i = 0; i < funcList.length; i++) {
243
                        if(funcList[i]) {
244
                                String fieldName = funcMap.get(Summary[i]);
245
                                if(fieldName.length() >= 6)
246
                                        fieldName = fieldName.substring(0, 7);
247
                                attr.add(fieldName + "_" + Summary[i]);
248
                                typesList.add(Double.class);
249
                        }
250
                }
251
                
252
                attr.add(NEW_FIELD);
253
                typesList.add(Integer.class);
254
                
255
                attrNames = new String[attr.size()];
256
                attr.toArray(attrNames);
257
                Class[] types = new Class[typesList.size()];
258
                typesList.toArray(types);
259
                
260
                try {
261
                        IVectorLayer output = getNewVectorLayer(sextanteLayerLabel,
262
                                                                                                        sextanteLayerName,
263
                                                                                                        shapeType, types, attrNames);
264
                        return ((FlyrVectIVectorLayer)output).getFeatureStore();
265
                } catch (UnsupportedOutputChannelException e) {
266
                        Sextante.addErrorToLog(e);
267
        } catch (GeoAlgorithmExecutionException e) {
268
            Sextante.addErrorToLog(e);
269
        }
270
                return null;
271
        }
272

    
273
    @Override
274
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
275
        return SpatialJoinParametersPanel.class;
276
    }
277
}