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 @ 336

History | View | Annotate | Download (10.7 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 org.gvsig.fmap.dal.DALLocator;
31
import org.gvsig.fmap.dal.DataManager;
32
import org.gvsig.fmap.dal.DataTypes;
33
import org.gvsig.fmap.dal.exception.DataException;
34
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
35
import org.gvsig.fmap.dal.feature.FeatureStore;
36
import org.gvsig.fmap.dal.feature.FeatureType;
37
import org.gvsig.geoprocess.algorithm.base.core.GeometryOperation;
38
import org.gvsig.geoprocess.algorithm.dissolve.DissolveRule;
39
import org.gvsig.geoprocess.algorithm.dissolve.IDissolveRule;
40
import org.gvsig.geoprocess.algorithm.dissolve.Summary;
41
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
42
import org.gvsig.geoprocess.lib.sextante.dataObjects.FlyrVectIVectorLayer;
43

    
44
import es.unex.sextante.core.Sextante;
45
import es.unex.sextante.dataObjects.IVectorLayer;
46
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
47
import es.unex.sextante.exceptions.RepeatedParameterNameException;
48
import es.unex.sextante.exceptions.UnsupportedOutputChannelException;
49
import es.unex.sextante.gui.algorithm.GeoAlgorithmParametersPanel;
50
import es.unex.sextante.outputs.OutputVectorLayer;
51

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

    
58
        public static final String        NEW_FIELD             = "NUM_RELA";
59
        public static final String        RESULT                = "RESULT";
60
        public static final String        LAYER1                = "LAYER1";
61
        public static final String        LAYER2                = "LAYER2";
62
        public static final String        SELECTGEOM_INPUT      = "SELECTGEOM_INPUT";
63
        public static final String        SELECTGEOM_OVERLAY    = "SELECTGEOM_OVERLAY";
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(SELECTGEOM_INPUT, 
89
                            getTranslation("Selected_geometries_input_layer"), false);
90
            m_Parameters.addBoolean(SELECTGEOM_OVERLAY, 
91
                            getTranslation("Selected_geometries_overlay_layer"), false);
92
            m_Parameters.addBoolean(NEAREST, getTranslation("use_the_nearest"), false);
93
            m_Parameters.addString(FUNCTION_LIST,
94
                getTranslation("Function_list"));
95
                } catch (RepeatedParameterNameException e) {
96
                        Sextante.addErrorToLog(e);
97
                }
98
                addOutputVectorLayer(RESULT,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
                if(existsOutPutFile(SpatialJoinAlgorithm.RESULT, 0)) {
108
                    throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
109
            }
110
                IVectorLayer layer1 = m_Parameters.getParameterValueAsVectorLayer(LAYER1);
111
                IVectorLayer layer2 = m_Parameters.getParameterValueAsVectorLayer(LAYER2);
112
                boolean selectedGeomInput = m_Parameters.getParameter(SELECTGEOM_INPUT).getParameterValueAsBoolean();
113
                boolean selectedGeomOverlay = m_Parameters.getParameter(SELECTGEOM_OVERLAY).getParameterValueAsBoolean();
114
                boolean nearest = m_Parameters.getParameterValueAsBoolean(NEAREST);
115
                String functionList = m_Parameters.getParameterValueAsString(FUNCTION_LIST);
116
                loadSummary(functionList);
117

    
118
                FlyrVectIVectorLayer lyr1 = null;
119
                FlyrVectIVectorLayer lyr2 = null;
120
                if(layer2 instanceof FlyrVectIVectorLayer && layer1 instanceof FlyrVectIVectorLayer) { 
121
                        lyr2 = ((FlyrVectIVectorLayer)layer2);
122
                        lyr1 = ((FlyrVectIVectorLayer)layer1);
123
                } else 
124
                        return false;
125

    
126
                DataManager dataManager = DALLocator.getDataManager();
127

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

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

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

    
188
                return true;
189
        }
190

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

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