Revision 955

View differences:

org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/test/java/org/gvsig/lrs/lib/impl/TestLineInterpolatePoint.java
1
package org.gvsig.lrs.lib.impl;
2

  
3
import junit.framework.TestCase;
4
import org.gvsig.fmap.geom.Geometry;
5
import org.gvsig.fmap.geom.GeometryLocator;
6
import org.gvsig.fmap.geom.GeometryManager;
7
import org.gvsig.fmap.geom.primitive.Point;
8
import org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs.STLineInterpolatePointFunction;
9
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
10

  
11
public class TestLineInterpolatePoint extends TestCase {
12
    
13
    public TestLineInterpolatePoint(String testName) {
14
        super(testName);
15
    }
16
    
17
    @Override
18
    protected void setUp() throws Exception {
19
        super.setUp();
20
        new DefaultLibrariesInitializer().fullInitialize();
21
    }
22
    
23
    @Override
24
    protected void tearDown() throws Exception {
25
        super.tearDown();
26
    }
27

  
28
    // TODO add test methods here. The name must begin with 'test'. For example:
29
    // public void testHello() {}
30
    
31
    public void testLine1() throws Exception{
32
        
33
        GeometryManager manager = GeometryLocator.getGeometryManager();
34
        Geometry line = manager.createFrom("LINESTRING (100 400, 400 400, 605 464, 800 460)");
35
        
36
        double fraction = 150/line.perimeter();
37
        
38
        Point point = STLineInterpolatePointFunction.lineInterpolatePoint(line, fraction);
39
        
40
        assertEquals("POINT (250 400)", point.convertToWKT());
41
    }
42

  
43
    public void testMultiLine1() throws Exception{
44
        
45
        GeometryManager manager = GeometryLocator.getGeometryManager();
46
        Geometry line = manager.createFrom("MULTILINESTRING ((100 400, 400 400),  (400 500, 600 500),  (600 500, 800 460))");
47

  
48
        double fraction = 400/line.perimeter();
49
        
50
        Point point = STLineInterpolatePointFunction.lineInterpolatePoint(line, fraction);
51
        
52
        assertEquals("POINT (500 500)", point.convertToWKT());
53
    }
54
    
55
    public void testLineM1() throws Exception{
56
        
57
        GeometryManager manager = GeometryLocator.getGeometryManager();
58
        Geometry line = manager.createFrom("LINESTRING M(100 400 0, 400 400 300, 605 464 505, 800 460 700)");
59
        
60
        double fraction = 150/line.perimeter();
61
        
62
        Point point = STLineInterpolatePointFunction.lineInterpolatePoint(line, fraction);
63
        
64
        assertEquals("POINT M (250 400 150)", point.convertToWKT());
65
    }
66

  
67
    public void testMultiLineM1() throws Exception{
68
        
69
        GeometryManager manager = GeometryLocator.getGeometryManager();
70
        Geometry line = manager.createFrom("MULTILINESTRING M((100 400 0, 400 400 300),  (400 500 300, 600 500 500),  (600 500 500, 800 460 700))");
71

  
72
        double fraction = 400/line.perimeter();
73
        
74
        Point point = STLineInterpolatePointFunction.lineInterpolatePoint(line, fraction);
75
        
76
        assertEquals("POINT M (500 500 400)", point.convertToWKT());
77
    }
78
    
79
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/test/java/org/gvsig/lrs/lib/impl/TestLineLocatePoint.java
1
package org.gvsig.lrs.lib.impl;
2

  
3
import junit.framework.TestCase;
4
import org.gvsig.fmap.geom.Geometry;
5
import org.gvsig.fmap.geom.GeometryLocator;
6
import org.gvsig.fmap.geom.GeometryManager;
7
import org.gvsig.fmap.geom.aggregate.MultiLine;
8
import org.gvsig.fmap.geom.primitive.Line;
9
import org.gvsig.fmap.geom.primitive.Point;
10
import org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs.STLineLocatePointFunction;
11
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
12

  
13
public class TestLineLocatePoint extends TestCase {
14
    
15
    public TestLineLocatePoint(String testName) {
16
        super(testName);
17
    }
18
    
19
    @Override
20
    protected void setUp() throws Exception {
21
        super.setUp();
22
        new DefaultLibrariesInitializer().fullInitialize();
23
    }
24
    
25
    @Override
26
    protected void tearDown() throws Exception {
27
        super.tearDown();
28
    }
29

  
30
    // TODO add test methods here. The name must begin with 'test'. For example:
31
    // public void testHello() {}
32
    
33
    public void testLine1() throws Exception{
34
        
35
        GeometryManager manager = GeometryLocator.getGeometryManager();
36
        Geometry line = manager.createFrom("LINESTRING (100 400, 400 400, 605 464, 800 460)");
37
        
38
        Geometry point = manager.createFrom("POINT (250 350)");
39
        
40
        double location = STLineLocatePointFunction.lineLocatePoint((Line)line, (Point)point);
41
        assertEquals(150/line.perimeter(), location);
42
    }
43

  
44
    public void testMultiLine1() throws Exception{
45
        
46
        GeometryManager manager = GeometryLocator.getGeometryManager();
47
        Geometry line = manager.createFrom("MULTILINESTRING ((100 400, 400 400),  (400 500, 600 500),  (600 500, 800 460))");
48
        
49
        Geometry point = manager.createFrom("POINT (500 450)");
50
        
51
        double location = STLineLocatePointFunction.lineLocatePoint((MultiLine)line, (Point)point);
52
        assertEquals(400/line.perimeter(), location);
53
    }
54
    
55
}
0 56

  
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/expressionevaluator/symboltable/LRSSymbolTableFactory.java
1
package org.gvsig.lrs.lib.impl.expressionevaluator.symboltable;
2

  
3
import org.gvsig.expressionevaluator.ExpressionEvaluatorLocator;
4
import org.gvsig.expressionevaluator.ExpressionEvaluatorManager;
5
import org.gvsig.expressionevaluator.SymbolTable;
6
import org.gvsig.expressionevaluator.spi.AbstractSymbolTableFactory;
7

  
8
/**
9
 *
10
 * @author jjdelcerro
11
 */
12
public class LRSSymbolTableFactory extends AbstractSymbolTableFactory {
13

  
14
    private SymbolTable symbolTable;
15
    
16
    public LRSSymbolTableFactory() {
17
        super(LRSSymbolTable.NAME, true);
18
    }
19
    
20
    @Override
21
    public SymbolTable create(Object... args) {
22
        if( this.symbolTable==null ) {
23
            this.symbolTable = new LRSSymbolTable();
24
        }
25
        return this.symbolTable;
26
    }
27
    
28
    public static final void selfRegister() {
29
        ExpressionEvaluatorManager manager = ExpressionEvaluatorLocator.getManager();
30
        
31
        manager.registerSymbolTable(new LRSSymbolTableFactory());
32
    }
33
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/expressionevaluator/symboltable/LRSSymbolTable.java
1
package org.gvsig.lrs.lib.impl.expressionevaluator.symboltable;
2

  
3
import org.gvsig.expressionevaluator.spi.AbstractSymbolTable;
4
import org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs.STLineInterpolatePointFunction;
5
import org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs.STLineLocatePointFunction;
6

  
7
/**
8
 *
9
 * @author jjdelcerro
10
 */
11
public class LRSSymbolTable extends AbstractSymbolTable {
12
    public static final String GROUP_LRS = "Linear reference system";
13
    
14
    static final String NAME = "Linear reference system";
15
    
16
    @SuppressWarnings("OverridableMethodCallInConstructor")
17
    public LRSSymbolTable() {
18
        super(NAME);
19

  
20
//        this.addFunction(new LRSPointFromGeometryFunction());
21
        this.addFunction(new STLineLocatePointFunction());
22
        this.addFunction(new STLineInterpolatePointFunction());
23
    }
24

  
25
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/expressionevaluator/function/lrs/STLineInterpolatePointFunction.java
1
package org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs;
2

  
3
import org.apache.commons.lang3.Range;
4
import org.gvsig.expressionevaluator.Interpreter;
5
import org.gvsig.expressionevaluator.spi.AbstractGeometryFunction;
6
import org.gvsig.fmap.geom.Geometry;
7
import org.gvsig.fmap.geom.aggregate.MultiLine;
8
import org.gvsig.fmap.geom.primitive.Line;
9
import org.gvsig.fmap.geom.primitive.Point;
10
import org.gvsig.lrs.lib.impl.expressionevaluator.symboltable.LRSSymbolTable;
11

  
12
public class STLineInterpolatePointFunction extends AbstractGeometryFunction {
13

  
14
    public static final String FUNCTION_ST_LINEINTERPOLATEPOINT = "ST_LineInterpolatePoint";
15
    
16
    public STLineInterpolatePointFunction() {
17
        super(
18
                LRSSymbolTable.GROUP_LRS,
19
                FUNCTION_ST_LINEINTERPOLATEPOINT,
20
                Range.is(2),
21
                "Returns a point interpolated along a line at a fractional location. First argument must be a LINESTRING. Second argument is a float between 0 and 1 representing the fraction of line length where the point is to be located. The Z and M values are interpolated if present.\n" +
22
                "See ST_LineLocatePoint for computing the line location nearest to a Point.",
23
                FUNCTION_ST_LINEINTERPOLATEPOINT + "( {{ a_linestring}},  a_fraction)",
24
                new String[]{
25
                    " a_linestring - a LineString with M coordinate.",
26
                    " a_fraction - the fractional location",},
27
                "Point",
28
                false
29
        );
30
    }
31

  
32
    @Override
33
    public boolean allowConstantFolding() {
34
        return true;
35
    }
36
    
37
    @Override
38
    public Object call(Interpreter interpreter, Object[] args) throws Exception {
39
        Geometry geom = this.getGeom(args, 0);
40
        double fraction = this.getDouble(args, 1);
41
        
42
        return lineInterpolatePoint(geom, fraction);
43
    }
44
    
45
    public static Point lineInterpolatePoint(Geometry geom, double fraction) throws Exception{
46
        double l = geom.perimeter();
47
        Point point;
48
        if (geom instanceof Line){
49
            point = ((Line)geom).extractPoint(fraction*l);
50
        } else if (geom instanceof MultiLine){
51
            point = ((MultiLine)geom).extractPoint(fraction*l);
52
        } else {
53
            throw new IllegalArgumentException("Need Line or MultiLine geometry.");
54
        }
55
        
56
        return point;
57
    }
58

  
59
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/expressionevaluator/function/lrs/STLineLocatePointFunction.java
1
package org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs;
2

  
3
import org.apache.commons.lang3.Range;
4
import org.gvsig.expressionevaluator.Interpreter;
5
import org.gvsig.expressionevaluator.spi.AbstractGeometryFunction;
6
import org.gvsig.fmap.geom.Geometry;
7
import org.gvsig.fmap.geom.aggregate.MultiLine;
8
import org.gvsig.fmap.geom.primitive.Line;
9
import org.gvsig.fmap.geom.primitive.Point;
10
import org.gvsig.lrs.lib.impl.expressionevaluator.symboltable.LRSSymbolTable;
11

  
12
public class STLineLocatePointFunction extends AbstractGeometryFunction {
13

  
14
    public static final String FUNCTION_ST_LINELOCATEPOINT = "ST_LineLocatePoint";
15
    
16
    public STLineLocatePointFunction() {
17
        super(
18
                LRSSymbolTable.GROUP_LRS,
19
                FUNCTION_ST_LINELOCATEPOINT,
20
                Range.is(2),
21
                "Returns a float between 0 and 1 representing the location of the closest point on a LineString to the given Point, as a fraction of 2d line length.\n"
22
                + "You can use the returned location to extract a Point (ST_LineInterpolatePoint) or a substring (ST_LineSubstring).\n"
23
                + "This is useful for approximating numbers of addresses\n",
24
                FUNCTION_ST_LINELOCATEPOINT + "( {{ a_linestring}},  a_point)",
25
                new String[]{
26
                    " a_linestring - a LineString with M coordinate.",
27
                    " a_point - a Point (with or without M coordinate) near of the LineString",},
28
                "Double",
29
                false
30
        );
31
    }
32

  
33
    @Override
34
    public boolean allowConstantFolding() {
35
        return true;
36
    }
37
    
38
    @Override
39
    public Object call(Interpreter interpreter, Object[] args) throws Exception {
40
        Geometry geom = this.getGeom(args, 0);
41
        Point point =this.getPoint(args, 1);
42
        
43
        return lineLocatePoint(geom, point);
44
    }
45
    
46
    public static double lineLocatePoint(Geometry geom, Point point) throws Exception{
47
        double l = geom.perimeter();
48
        double locatePoint;
49
        if (geom instanceof Line){
50
            locatePoint = ((Line)geom).getPathLength(point);
51
        } else if (geom instanceof MultiLine){
52
            locatePoint = ((MultiLine)geom).getPathLength(point);
53
        } else {
54
            throw new IllegalArgumentException("Need Line or MultiLine geometry.");
55
        }
56
        
57
        double fraction = locatePoint / l;
58
        
59
        return fraction;
60
    }
61

  
62
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/expressionevaluator/function/lrs/LRSPointFromGeometryFunction.java
1
package org.gvsig.lrs.lib.impl.expressionevaluator.function.lrs;
2

  
3
import org.apache.commons.lang3.Range;
4
import org.gvsig.expressionevaluator.Interpreter;
5
import org.gvsig.expressionevaluator.spi.AbstractGeometryFunction;
6
import org.gvsig.fmap.geom.Geometry;
7
import org.gvsig.fmap.geom.primitive.Point;
8
import org.gvsig.lrs.lib.api.LrsAlgorithmsLocator;
9
import org.gvsig.lrs.lib.api.LrsAlgorithmsManager;
10
import org.gvsig.lrs.lib.impl.expressionevaluator.symboltable.LRSSymbolTable;
11

  
12
public class LRSPointFromGeometryFunction extends AbstractGeometryFunction {
13

  
14
    public static final String FUNCTION_LRSPOINTFROMGEOMETRY = "LRSPointFromGeometry";
15
    
16
    public LRSPointFromGeometryFunction() {
17
        super(
18
                LRSSymbolTable.GROUP_LRS, 
19
                FUNCTION_LRSPOINTFROMGEOMETRY, 
20
                Range.is(2),
21
                "Returns ?????? TODO.\n",
22
                FUNCTION_LRSPOINTFROMGEOMETRY+"( {{geom}}, point_or_distance)",
23
                new String[]{
24
                    "geom - TODO.",
25
                    "point_or_distance - TODO",
26
                },
27
                "Point",
28
                false
29
        );
30
    }
31

  
32
    @Override
33
    public boolean allowConstantFolding() {
34
        return true;
35
    }
36
    
37
    @Override
38
    public Object call(Interpreter interpreter, Object[] args) throws Exception {
39
        Geometry geom = this.getGeom(args, 0);
40
        Object v2 = this.getObject(args, 1);
41

  
42
        LrsAlgorithmsManager manager = LrsAlgorithmsLocator.getLrsAlgorithmsManager();
43
        Point r = null;
44
        if( v2 instanceof Number ) {
45
            double distance = this.getDouble(args, 1);
46
            r = manager.getMPointFromGeometry(geom, distance);
47
        } else {
48
            Point point =this.getPoint(args, 1);
49
            r = manager.getMPointFromGeometry(geom, point);
50
        }
51
        return r;
52
    }
53

  
54
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/DefaultLrsCreateRouteAlgorithmParams.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.lib.impl;
24

  
25
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
26
import org.gvsig.fmap.dal.feature.FeatureStore;
27
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
28
import org.gvsig.lrs.lib.api.LrsCoordinatesPriority;
29
import org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams;
30
import org.gvsig.lrs.lib.api.LrsSourceOfMeasures;
31

  
32

  
33
/**
34
 * @author fdiaz
35
 *
36
 */
37
public class DefaultLrsCreateRouteAlgorithmParams implements LrsCreateRouteAlgorithmParams {
38

  
39
    private FeatureStore sourceFeatureStore;
40
    private FeatureAttributeDescriptor idRouteField;
41
    private NewFeatureStoreParameters newFeatureStoreParameters;
42
    private LrsSourceOfMeasures sourceOfMeasures;
43
    private FeatureAttributeDescriptor fromMeasureField;
44
    private FeatureAttributeDescriptor toMeasureField;
45
    private LrsCoordinatesPriority coordinatePriority;
46
    private double measureFactor = 1.0;
47
    private double measureOffset = 0.0;
48
    private boolean ignoreSpatialGaps;
49
    private final String NAME = "LrsCreateRouteAlgorithm";
50
    private final String DESCRIPTION = "Algorithm to create routes with linear reference system.";
51

  
52

  
53

  
54
    /**
55
     *
56
     */
57
    public DefaultLrsCreateRouteAlgorithmParams() {
58
        measureFactor = 1.0;
59
        measureOffset = 0.0;
60
    }
61

  
62
    /* (non-Javadoc)
63
     * @see org.gvsig.lrs.lib.api.LrsAlgorithmParams#getName()
64
     */
65
    public String getName() {
66
        return NAME;
67
    }
68

  
69
    /* (non-Javadoc)
70
     * @see org.gvsig.lrs.lib.api.LrsAlgorithmParams#getDescription()
71
     */
72
    public String getDescription() {
73
        return DESCRIPTION;
74
    }
75

  
76
    /*
77
     * (non-Javadoc)
78
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getSourceFeatureStore()
79
     */
80
    public FeatureStore getSourceFeatureStore() {
81
        return sourceFeatureStore;
82
    }
83

  
84

  
85
    /*
86
     * (non-Javadoc)
87
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setSourceFeatureStore(org.gvsig.fmap.dal.feature.FeatureStore)
88
     */
89
    public void setSourceFeatureStore(FeatureStore sourceFeatureStore) {
90
        this.sourceFeatureStore = sourceFeatureStore;
91
    }
92

  
93
    /*
94
     * (non-Javadoc)
95
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getIdRouteField()
96
     */
97
    public FeatureAttributeDescriptor getIdRouteField() {
98
        return idRouteField;
99
    }
100

  
101

  
102
    /*
103
     * (non-Javadoc)
104
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setIdRouteField(org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor)
105
     */
106
    public void setIdRouteField(FeatureAttributeDescriptor idRouteField) {
107
        this.idRouteField = idRouteField;
108
    }
109

  
110
    /*
111
     * (non-Javadoc)
112
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getSourceOfMeasures()
113
     */
114
    public LrsSourceOfMeasures getSourceOfMeasures() {
115
        return sourceOfMeasures;
116
    }
117

  
118
    /*
119
     * (non-Javadoc)
120
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setSourceOfMeasures(org.gvsig.lrs.lib.api.SourceOfMeasures)
121
     */
122
    public void setSourceOfMeasures(LrsSourceOfMeasures sourceOfMeasures) {
123
        this.sourceOfMeasures = sourceOfMeasures;
124
    }
125

  
126
    /*
127
     * (non-Javadoc)
128
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getFromMeasureField()
129
     */
130
    public FeatureAttributeDescriptor getFromMeasureField() {
131
        return fromMeasureField;
132
    }
133

  
134
    /*
135
     * (non-Javadoc)
136
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setFromMeasureField(org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor)
137
     */
138
    public void setFromMeasureField(FeatureAttributeDescriptor fromMeasureField) {
139
        this.fromMeasureField = fromMeasureField;
140
    }
141

  
142
    /*
143
     * (non-Javadoc)
144
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getToMeasureField()
145
     */
146
    public FeatureAttributeDescriptor getToMeasureField() {
147
        return toMeasureField;
148
    }
149

  
150
    /*
151
     * (non-Javadoc)
152
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setToMeasureField(org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor)
153
     */
154
    public void setToMeasureField(FeatureAttributeDescriptor toMeasureField) {
155
        this.toMeasureField = toMeasureField;
156
    }
157

  
158
    /*
159
     * (non-Javadoc)
160
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getCoordinatePriority()
161
     */
162
    public LrsCoordinatesPriority getCoordinatePriority() {
163
        return coordinatePriority;
164
    }
165

  
166
    /*
167
     * (non-Javadoc)
168
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setCoordinatePriority(org.gvsig.lrs.lib.api.CoordinatesPriority)
169
     */
170
    public void setCoordinatePriority(LrsCoordinatesPriority coordinatePriority) {
171
        this.coordinatePriority = coordinatePriority;
172
    }
173

  
174
    /*
175
     * (non-Javadoc)
176
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getMeasureFactor()
177
     */
178
    public double getMeasureFactor() {
179
        return measureFactor;
180
    }
181

  
182
    /*
183
     * (non-Javadoc)
184
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setMeasureFactor(double)
185
     */
186
    public void setMeasureFactor(double measureFactor) {
187
        this.measureFactor = measureFactor;
188
    }
189

  
190
    /*
191
     * (non-Javadoc)
192
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#getMeasureOffset()
193
     */
194
    public double getMeasureOffset() {
195
        return measureOffset;
196
    }
197

  
198
    /*
199
     * (non-Javadoc)
200
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setMeasureOffset(double)
201
     */
202
    public void setMeasureOffset(double measureOffset) {
203
        this.measureOffset = measureOffset;
204
    }
205

  
206
    /*
207
     * (non-Javadoc)
208
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#isIgnoreSpatialGaps()
209
     */
210
    public boolean ignoreSpatialGaps() {
211
        return ignoreSpatialGaps;
212
    }
213

  
214
    /*
215
     * (non-Javadoc)
216
     * @see org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams#setIgnoreSpatialGaps(boolean)
217
     */
218
    public void setIgnoreSpatialGaps(boolean ignoreSpatialGaps) {
219
        this.ignoreSpatialGaps = ignoreSpatialGaps;
220
    }
221

  
222
    public NewFeatureStoreParameters getNewFeatureStoreParameters() {
223
        return this.newFeatureStoreParameters;
224
    }
225

  
226
    public void setNewFeatureStoreParameters(
227
        NewFeatureStoreParameters newFeatureStoreParameters) {
228
        this.newFeatureStoreParameters = newFeatureStoreParameters;
229
    }
230

  
231
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/DefaultMeasuresCalculator.java
1
package org.gvsig.lrs.lib.impl;
2

  
3
import org.gvsig.lrs.lib.api.MeasuresCalculator;
4
import java.util.ArrayList;
5
import java.util.List;
6
import org.gvsig.fmap.geom.Geometry;
7
import org.gvsig.fmap.geom.GeometryLocator;
8
import org.gvsig.fmap.geom.GeometryManager;
9
import org.gvsig.fmap.geom.operation.GeometryOperationException;
10
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
11
import org.gvsig.fmap.geom.primitive.Line;
12
import org.gvsig.fmap.geom.primitive.Point;
13
import org.gvsig.lrs.lib.api.LrsMeasureCalculationMethods;
14
import org.slf4j.Logger;
15
import org.slf4j.LoggerFactory;
16

  
17
class DefaultMeasuresCalculator implements MeasuresCalculator {
18

  
19
    private static final Logger logger = LoggerFactory.getLogger(DefaultMeasuresCalculator.class);
20

  
21
    private Geometry route;
22
    private List<Boolean> isFixedPoint;
23
    private List<Double> distances;
24
    private List<Double> oldMValues;
25
    private List<Point> vertices;
26
    private List<Integer> lineIndexes;
27
    private int MDIMENSION;
28

  
29
    private final Double PRECISION = new Double(1.0e-5);
30

  
31
    @Override
32
    public Geometry getResult() {
33
        return route;
34
    }
35

  
36
    public DefaultMeasuresCalculator(Geometry geometry, boolean ignoreSpatialGaps) {
37
        isFixedPoint = new ArrayList<Boolean>();
38
        distances = new ArrayList<Double>();
39
        oldMValues = new ArrayList<Double>();
40
        vertices = new ArrayList<Point>();
41
        lineIndexes = new ArrayList<Integer>();
42
        route = geometry.cloneGeometry();
43

  
44
        double distance = 0;
45
        List<Line> lines = LrsAlgorithmUtils.extractLines(geometry);
46
        Point previousVertex = null;
47
        for (int i = 0; i < lines.size(); i++) {
48
            Line line = lines.get(i);
49
            for (int j = 0; j < line.getNumVertices(); j++) {
50
                Point vertex = line.getVertex(j);
51
                if (j == 0) {
52
                    if (previousVertex == null) {
53
                        //First point in geometry
54
                        MDIMENSION = vertex.getDimension() - 1;
55
                        distance = 0;
56
                    }
57
                    Integer visitedIndex = getIndexVisitedVertex(vertex);
58
                    if (visitedIndex != null) {
59
                        previousVertex = vertices.get(visitedIndex);
60
                        distance = distances.get(visitedIndex);
61
                    } else {
62
                        if (previousVertex != null) {
63
                            try {
64
                                if (!LrsAlgorithmUtils.equalPoints(vertex, previousVertex)) {
65
                                    Integer nearestVertexPos = getIndexNearestVisitedVertex(vertex);
66
                                    if (ignoreSpatialGaps) {
67
                                        distance = distances.get(nearestVertexPos);
68
                                    } else {
69
                                        Point nearestVertex = vertices.get(nearestVertexPos);
70
                                        distance = distances.get(nearestVertexPos);
71
                                        distance += vertex.distance(nearestVertex);
72
                                    }
73
                                }
74
                            } catch (Exception e) {
75
                                distance = Double.NaN;
76
                            }
77
                        }
78
                    }
79
                } else {
80
                    try {
81
                        distance += vertex.distance(previousVertex);
82
                    } catch (Exception e) {
83
                        distance = Double.NaN;
84
                    }
85
                }
86
                Double mValue = vertex.getCoordinateAt(MDIMENSION);
87

  
88
                isFixedPoint.add(false);
89
                vertices.add(vertex);
90
                distances.add(distance);
91
                oldMValues.add(mValue);
92
                lineIndexes.add(i);
93

  
94
                previousVertex = vertex;
95
            }
96
        }
97
    }
98

  
99
    private Integer getIndexNearestVisitedVertex(Point vertex) throws GeometryOperationNotSupportedException, GeometryOperationException {
100
        double nearestDistance = Double.POSITIVE_INFINITY;
101
        Integer nearestPointPos = null;
102
        for (int i = 0; i < vertices.size(); i++) {
103
            Double distance = vertex.distance(vertices.get(i));
104
            if (nearestDistance > distance && distance > Double.valueOf(0)) {
105
                nearestDistance = distance;
106
                nearestPointPos = i;
107
            }
108
        }
109
        return nearestPointPos;
110
    }
111

  
112
    private Integer getIndexVisitedVertex(Point point) {
113
        double distance = Double.NEGATIVE_INFINITY;
114
        Integer index = null;
115
        for (int i = 0; i < vertices.size(); i++) {
116
            if (LrsAlgorithmUtils.equalPoints(point, vertices.get(i))) {
117
                if (this.distances.get(i) > distance) {
118
                    distance = this.distances.get(i);
119
                    index = i;
120
                }
121
            }
122
        }
123
        return index;
124
    }
125

  
126
    @Override
127
    public void addControlPoints(List<Point> fixedPoints) {
128
        for (Point fixedPoint : fixedPoints) {
129
            Double length = Double.valueOf(0);
130
            int index = 0;
131
            List<Line> lines = LrsAlgorithmUtils.extractLines(route);
132
            List<Integer> insertAtList = new ArrayList<Integer>();
133
            List<Double> lengths = new ArrayList<Double>();
134
            List<Double> oldValues = new ArrayList<Double>();
135
            List<Integer> lineReference = new ArrayList<Integer>();
136
            for (int i = 0; i < lines.size(); i++) {
137
                Line line = lines.get(i);
138
                try {
139
                    if (line.isWithinDistance(fixedPoint, PRECISION)) {
140
                        length = distances.get(index);
141
                        for (int j = 0; j < line.getNumVertices(); j++) {
142
                            Point vertex = line.getVertex(j);
143
                            Point nextVertex;
144
                            if (j + 1 < line.getNumVertices()) {
145
                                nextVertex = line.getVertex(j + 1);
146
                            } else {
147
                                nextVertex = null;
148
                            }
149
                            if (LrsAlgorithmUtils.equalPoints(vertex, fixedPoint) || vertex.distance(fixedPoint) <= PRECISION) {
150
                                oldMValues.set(index, vertex.getCoordinateAt(MDIMENSION));
151
                                Double mValue = fixedPoint.getCoordinateAt(MDIMENSION);
152
                                vertex.setCoordinateAt(MDIMENSION, mValue);
153
                                isFixedPoint.set(index, true);
154
                                vertices.set(index, vertex);
155
                            } else {
156
                                if (nextVertex != null
157
                                        && !LrsAlgorithmUtils.equalPoints(nextVertex, fixedPoint)
158
                                        && vertex.distance(fixedPoint) > PRECISION
159
                                        && nextVertex.distance(fixedPoint) > PRECISION) {
160

  
161
                                    GeometryManager geomanager = GeometryLocator.getGeometryManager();
162
                                    Line segment = (Line) geomanager
163
                                            .create(Geometry.TYPES.LINE, Geometry.SUBTYPES.GEOM2DM);
164
                                    segment.addVertex(vertex);
165
                                    segment.addVertex(nextVertex);
166
                                    //FIXME
167
                                    //if (line.intersects(fixedPoint)){
168
                                    if (segment.isWithinDistance(fixedPoint, PRECISION)) {
169
                                        double distanceFirstVertex = distances.get(index);
170
                                        double distanceToFixedPoint = vertex.distance(fixedPoint);
171
                                        length = distanceFirstVertex + distanceToFixedPoint;
172
                                        Double oldMValue = LrsAlgorithmUtils.straightLineThroughTwoPointsEquation(
173
                                                distances.get(index),
174
                                                distances.get(index + 1),
175
                                                vertex.getCoordinateAt(MDIMENSION),
176
                                                nextVertex.getCoordinateAt(MDIMENSION),
177
                                                length);
178
                                        insertAtList.add(index + 1);
179
                                        lengths.add(length);
180
                                        oldValues.add(oldMValue);
181
                                        lineReference.add(i);
182
                                    }
183
                                }
184
                            }
185
                            index++;
186
                        }
187
                    } else {
188
                        index += line.getNumVertices();
189
                    }
190
                } catch (Exception e) {
191
                    logger.warn("Error inserting point " + fixedPoint.toString(), e);
192
                }
193
            }
194
            int pos = 0;
195
            for (Integer insertAt : insertAtList) {
196
                Double distance = lengths.get(pos);
197
                Double oldMValue = oldValues.get(pos);
198
                Integer linePos = lineReference.get(pos);
199
                int correctedPosition = insertAt + pos;
200
                route = LrsAlgorithmUtils.insertVertex(route, fixedPoint, correctedPosition);
201
                isFixedPoint.add(correctedPosition, true);
202
                distances.add(correctedPosition, distance);
203
                oldMValues.add(correctedPosition, oldMValue);
204
                lineIndexes.add(correctedPosition, linePos);
205
                vertices.add(correctedPosition, fixedPoint);
206
                pos++;
207
            }
208
        }
209
    }
210

  
211
    @Override
212
    public void setFirstMeasure(double mvalue) {
213
        Point mPoint = (Point) this.vertices.get(0).cloneGeometry();
214
        int mDimension = mPoint.getDimension() - 1;
215
        mPoint.setCoordinateAt(mDimension, mvalue);
216
        List<Point> points = new ArrayList<>();
217
        points.add(mPoint);
218
        this.addControlPoints(points);
219
    }
220

  
221
    @Override
222
    public void setLastMeasure(double mvalue) {
223
        Point mPoint = (Point) this.vertices.get(this.vertices.size()-1).cloneGeometry();
224
        int mDimension = mPoint.getDimension() - 1;
225
        mPoint.setCoordinateAt(mDimension, mvalue);
226
        List<Point> points = new ArrayList<>();
227
        points.add(mPoint);
228
        this.addControlPoints(points);
229
    }
230

  
231
    @Override
232
    public void setMeasuresToDistances() {
233
        List<Point> points = LrsAlgorithmUtils.extractPoints(route);
234
        for (int i = 0; i < points.size(); i++) {
235
            if (!isFixedPoint.get(i)) {
236
                points.get(i).setCoordinateAt(MDIMENSION, distances.get(i));
237
                vertices.get(i).setCoordinateAt(MDIMENSION, distances.get(i));
238
                oldMValues.set(i, distances.get(i));
239
            }
240
        }
241
    }
242

  
243
    @Override
244
	public void calculate() {
245
        this.calculate(
246
                LrsMeasureCalculationMethods.DISTANCE,
247
                false,
248
                true,
249
                false
250
        );
251
    }
252
    
253
    @Override
254
    public void calculate(LrsMeasureCalculationMethods calculationMethod, boolean before, boolean between, boolean after) {
255
        for (int i = 0; i < vertices.size(); i++) {
256
            if (!isFixedPoint.get(i)) {
257
                Integer prevFixedPointPos = getPreviousPosFixedPoint(i);
258
                Integer nextFixedPointPos = getNextPosFixedPoint(i, false);
259

  
260
                if (prevFixedPointPos == null && nextFixedPointPos != null && before) {
261
                    extrapolateBeforeCalibrationPoints(calculationMethod, nextFixedPointPos, i);
262
                }
263
                if (prevFixedPointPos != null && nextFixedPointPos != null && between) {
264
                    calculateMValue(calculationMethod, prevFixedPointPos, nextFixedPointPos, i);
265
                }
266
                if (prevFixedPointPos != null && nextFixedPointPos == null && after) {
267
                    extrapolateAfterCalibrationPoints(calculationMethod, prevFixedPointPos, i);
268
                }
269
            }
270
        }
271
    }
272

  
273
    private void extrapolateBeforeCalibrationPoints(LrsMeasureCalculationMethods calculationMethod, int firstFixedPointPos, int pos) {
274
        Integer secondFixedPointPos = getNextPosFixedPoint(firstFixedPointPos, false);
275
        if (secondFixedPointPos != null) {
276

  
277
            if (calculationMethod.equals(LrsMeasureCalculationMethods.DISTANCE)) {
278
                if (!isFixedPoint.get(pos)) {
279
                    List<Point> points = LrsAlgorithmUtils.extractPoints(route);
280
                    points.get(pos).setCoordinateAt(MDIMENSION, distances.get(pos));
281
                    vertices.get(pos).setCoordinateAt(MDIMENSION, distances.get(pos));
282
                    oldMValues.set(pos, distances.get(pos));
283
                }
284
            }
285

  
286
            Double newMValueFirstPoint = vertices.get(firstFixedPointPos).getCoordinateAt(MDIMENSION);
287
            Double newMValueSecondPoint = vertices.get(secondFixedPointPos).getCoordinateAt(MDIMENSION);
288

  
289
            Double oldMValueFirstPoint;
290
            Double oldMValueSecondPoint;
291
            if (calculationMethod.equals(LrsMeasureCalculationMethods.DISTANCE)) {
292
                oldMValueFirstPoint = distances.get(firstFixedPointPos);
293
                oldMValueSecondPoint = distances.get(secondFixedPointPos);
294
            } else {
295
                oldMValueFirstPoint = oldMValues.get(firstFixedPointPos);
296
                oldMValueSecondPoint = oldMValues.get(secondFixedPointPos);
297
            }
298

  
299
            Double distanceBetweenFixedPoints = newMValueSecondPoint - newMValueFirstPoint;
300
            Double distanceBetweenOldFixedPoints = oldMValueSecondPoint - oldMValueFirstPoint;
301

  
302
            Double calibrationRatio = distanceBetweenOldFixedPoints / distanceBetweenFixedPoints;
303

  
304
            Double valueToRecalculate = vertices.get(pos).getCoordinateAt(MDIMENSION);
305
            Double distanceBetween = oldMValueFirstPoint - valueToRecalculate;
306
            Double mValue = newMValueFirstPoint - (distanceBetween / calibrationRatio);
307
            refreshMValueGeometryVertex(pos, mValue, false);
308
        }
309
    }
310

  
311
    private void extrapolateAfterCalibrationPoints(LrsMeasureCalculationMethods calculationMethod, int lastFixedPointPos, int pos) {
312
        Integer prevFixedPointPos = getPreviousPosFixedPoint(lastFixedPointPos);
313
        if (prevFixedPointPos != null) {
314
            calculateMValue(calculationMethod, prevFixedPointPos, lastFixedPointPos, pos);
315
        }
316
    }
317

  
318
    private void calculateMValue(LrsMeasureCalculationMethods calculationMethod, Integer prevFixedPointPos, int nextFixedPointPos, int pos) {
319

  
320
        if (calculationMethod.equals(LrsMeasureCalculationMethods.DISTANCE)) {
321
            if (!isFixedPoint.get(pos)) {
322
                List<Point> points = LrsAlgorithmUtils.extractPoints(route);
323
                points.get(pos).setCoordinateAt(MDIMENSION, distances.get(pos));
324
                vertices.get(pos).setCoordinateAt(MDIMENSION, distances.get(pos));
325
                oldMValues.set(pos, distances.get(pos));
326
            }
327
        }
328

  
329
        Double newMValueBeforePoint = vertices.get(prevFixedPointPos).getCoordinateAt(MDIMENSION);
330
        Double newMValueAfterPoint = vertices.get(nextFixedPointPos).getCoordinateAt(MDIMENSION);
331
        while (newMValueBeforePoint.equals(newMValueAfterPoint)) {
332
            prevFixedPointPos = getPreviousPosFixedPoint(prevFixedPointPos);
333
            if (prevFixedPointPos != null) {
334
                newMValueBeforePoint = vertices.get(prevFixedPointPos).getCoordinateAt(MDIMENSION);
335
            } else {
336
                refreshMValueGeometryVertex(pos, Double.NaN, false);
337
                return;
338
            }
339
        }
340

  
341
        Double oldMValueBeforePoint;
342
        Double oldMValueAfterPoint;
343
        if (calculationMethod.equals(LrsMeasureCalculationMethods.DISTANCE)) {
344
            oldMValueBeforePoint = distances.get(prevFixedPointPos);
345
            oldMValueAfterPoint = distances.get(nextFixedPointPos);
346
        } else {
347
            oldMValueBeforePoint = oldMValues.get(prevFixedPointPos);
348
            oldMValueAfterPoint = oldMValues.get(nextFixedPointPos);
349
        }
350

  
351
        Double distanceBetweenFixedPoints = newMValueAfterPoint - newMValueBeforePoint;
352
        Double distanceBetweenOldFixedPoints = oldMValueAfterPoint - oldMValueBeforePoint;
353

  
354
        Double calibrationRatio = distanceBetweenOldFixedPoints / distanceBetweenFixedPoints;
355

  
356
        Double valueToRecalculate = vertices.get(pos).getCoordinateAt(MDIMENSION);
357
        Double distanceBetween = valueToRecalculate - oldMValueBeforePoint;
358
        Double mValue = newMValueBeforePoint + (distanceBetween / calibrationRatio);
359
        refreshMValueGeometryVertex(pos, mValue, true);
360
    }
361

  
362
    private Integer getNextPosFixedPoint(int pos, boolean selfInclude) {
363
        Integer nextFixedPointPos = findNextFixedPointInLine(pos, selfInclude);
364
        if (nextFixedPointPos != null) {
365
            return nextFixedPointPos;
366
        } else {
367
            int lastPositionInLine = getLastPositionInLine(pos);
368
            nextFixedPointPos = findNextFixedPointInNextLines(lastPositionInLine, new ArrayList<Integer>());
369
            if (nextFixedPointPos != null) {
370
                return nextFixedPointPos;
371
            }
372
            try {
373
                Integer nearestVertex = findNearestNextPoint(lastPositionInLine);
374
                return getNextPosFixedPoint(nearestVertex, true);
375
            } catch (Exception e) {
376
                return null;
377
            }
378
        }
379
    }
380

  
381
    private Integer getLastPositionInLine(int pos) {
382
        Integer lineVisited = lineIndexes.get(pos);
383
        for (int i = pos + 1; i < vertices.size(); i++) {
384
            if (!lineVisited.equals(lineIndexes.get(i))) {
385
                return i - 1;
386
            }
387
        }
388
        return vertices.size() - 1;
389
    }
390

  
391
    private Integer findNextFixedPointInNextLines(int pos, List<Integer> visitedLines) {
392
        Integer nextFixedPointPos = findNextFixedPointInLine(pos, true);
393
        if (nextFixedPointPos != null) {
394
            return nextFixedPointPos;
395
        } else {
396
            Integer lineIndex = lineIndexes.get(pos);
397
            visitedLines.add(lineIndex);
398
            int lastPositionInLine = getLastPositionInLine(pos);
399
            Point lastVertexInLine = vertices.get(lastPositionInLine);
400
            for (int i = lastPositionInLine; i < vertices.size(); i++) {
401
                if (LrsAlgorithmUtils.equalPoints(lastVertexInLine, vertices.get(i))) {
402
                    if (!visitedLines.contains(lineIndexes.get(i))) {
403
                        findNextFixedPointInNextLines(i, visitedLines);
404
                    }
405
                }
406
            }
407
        }
408
        return null;
409
    }
410

  
411
    private Integer findNextFixedPointInLine(int vertexPos, boolean selfInclude) {
412
        int lineIndex = lineIndexes.get(vertexPos);
413
        if (!selfInclude) {
414
            vertexPos += 1;
415
        }
416
        for (int i = vertexPos; i < vertices.size(); i++) {
417
            if (!lineIndexes.get(i).equals(lineIndex)) {
418
                return null;
419
            }
420
            if (isFixedPoint.get(i)) {
421
                return i;
422
            }
423
        }
424
        return null;
425
    }
426

  
427
    private Integer findNearestNextPoint(int vertexPos) throws GeometryOperationNotSupportedException, GeometryOperationException {
428
        Point vertex = vertices.get(vertexPos);
429
        double nearestDistance = Double.POSITIVE_INFINITY;
430
        Integer nearestPointPos = null;
431
        for (int i = vertexPos + 1; i < vertices.size(); i++) {
432
            Double distance = vertex.distance(vertices.get(i));
433
            if (nearestDistance > distance && distance > Double.valueOf(0)) {
434
                nearestDistance = distance;
435
                nearestPointPos = i;
436
            }
437
        }
438
        return nearestPointPos;
439
    }
440

  
441
    private Integer getPreviousPosFixedPoint(int pos) {
442
        Integer prevFixedPointPos = findPrevFixedPointInLine(pos);
443
        if (prevFixedPointPos != null) {
444
            return prevFixedPointPos;
445
        } else {
446
            Integer lineVisited = lineIndexes.get(pos);
447
            for (int i = pos - 1; i >= 0; i--) {
448
                if (!lineVisited.equals(lineIndexes.get(i))) {//Line has changed
449
                    int lastPositionInLine = i + 1;
450
                    for (int j = lastPositionInLine; j >= 0; j--) {
451
                        if (LrsAlgorithmUtils.equalPoints(vertices.get(lastPositionInLine), vertices.get(j))) {
452
                            if (isFixedPoint.get(j) && j < pos) {
453
                                return j;
454
                            }
455
                        }
456
                    }
457
                    try {
458
                        return findNearestPrevFixedPoint(lastPositionInLine);
459
                    } catch (Exception e) {
460
                        return null;
461
                    }
462
                }
463
            }
464
        }
465
        return null;
466
    }
467

  
468
    private Integer findPrevFixedPointInLine(int vertexPos) {
469
        int lineIndex = lineIndexes.get(vertexPos);
470
        for (int i = vertexPos - 1; i >= 0; i--) {
471
            if (!lineIndexes.get(i).equals(lineIndex)) {
472
                return null;
473
            }
474
            if (isFixedPoint.get(i)) {
475
                return i;
476
            }
477
        }
478
        return null;
479
    }
480

  
481
    private Integer findNearestPrevFixedPoint(int vertexPos) throws GeometryOperationNotSupportedException, GeometryOperationException {
482
        Point vertex = vertices.get(vertexPos);
483
        double nearestDistance = Double.POSITIVE_INFINITY;
484
        Integer nearestPointPos = null;
485
        for (int i = vertexPos - 1; i >= 0; i--) {
486
            if (isFixedPoint.get(i)) {
487
                Double distance = vertex.distance(vertices.get(i));
488
                if (nearestDistance > distance) {
489
                    nearestDistance = distance;
490
                    nearestPointPos = i;
491
                }
492
            }
493
        }
494
        return nearestPointPos;
495
    }
496

  
497
    private void refreshMValueGeometryVertex(int i, Double mValue, boolean fixed) {
498
        List<Point> points = LrsAlgorithmUtils.extractPoints(route);
499
        vertices.get(i).setCoordinateAt(MDIMENSION, mValue);
500
        points.get(i).setCoordinateAt(MDIMENSION, mValue);
501
        isFixedPoint.set(i, fixed);
502
    }
503

  
504
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/DefaultLrsAlgorithmsLibrary.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright ? 2007-2015 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

  
25
package org.gvsig.lrs.lib.impl;
26

  
27
import org.gvsig.lrs.lib.api.LrsAlgorithmsLibrary;
28
import org.gvsig.lrs.lib.api.LrsAlgorithmsLocator;
29
import org.gvsig.lrs.lib.impl.expressionevaluator.symboltable.LRSSymbolTableFactory;
30
import org.gvsig.tools.library.AbstractLibrary;
31
import org.gvsig.tools.library.LibraryException;
32

  
33
/**
34
 * @author fdiaz</a>
35
 *
36
 */
37
public class DefaultLrsAlgorithmsLibrary extends AbstractLibrary {
38

  
39
    @Override
40
    public void doRegistration() {
41
        registerAsImplementationOf(LrsAlgorithmsLibrary.class);
42
    }
43

  
44
    @Override
45
    protected void doInitialize() throws LibraryException {
46
        LrsAlgorithmsLocator.registerLrsAlgorithmsManager(DefaultLrsAlgorithmsManager.class);
47
    }
48

  
49
    @Override
50
    protected void doPostInitialize() throws LibraryException {
51
        LRSSymbolTableFactory.selfRegister();
52
    }
53

  
54
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.174/org.gvsig.lrs.lib/org.gvsig.lrs.lib.impl/src/main/java/org/gvsig/lrs/lib/impl/LrsGenerateDynamicSegmentationAlgorithm.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.lib.impl;
24

  
25
import java.io.File;
26
import java.util.Iterator;
27
import java.util.List;
28

  
29
import org.apache.commons.lang3.StringUtils;
30
import org.slf4j.Logger;
31
import org.slf4j.LoggerFactory;
32

  
33
import org.gvsig.fmap.dal.DALLocator;
34
import org.gvsig.fmap.dal.DataManager;
35
import org.gvsig.fmap.dal.DataServerExplorer;
36
import org.gvsig.fmap.dal.DataServerExplorerParameters;
37
import org.gvsig.fmap.dal.DataStore;
38
import static org.gvsig.fmap.dal.DataStore.SHAPE_PROVIDER_NAME;
39
import org.gvsig.fmap.dal.DataTypes;
40
import org.gvsig.fmap.dal.feature.EditableFeature;
41
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
42
import org.gvsig.fmap.dal.feature.EditableFeatureType;
43
import org.gvsig.fmap.dal.feature.Feature;
44
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
45
import org.gvsig.fmap.dal.feature.FeatureQuery;
46
import org.gvsig.fmap.dal.feature.FeatureSet;
47
import org.gvsig.fmap.dal.feature.FeatureStore;
48
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
49
//import org.gvsig.fmap.dal.store.shp.SHPNewStoreParameters;
50
//import org.gvsig.fmap.dal.store.shp.SHPStoreProvider;
51
import org.gvsig.fmap.geom.Geometry;
52
import org.gvsig.fmap.geom.GeometryLocator;
53
import org.gvsig.fmap.geom.aggregate.MultiLine;
54
import org.gvsig.fmap.geom.primitive.Point;
55
import org.gvsig.fmap.geom.type.GeometryType;
56
import org.gvsig.lrs.lib.api.LrsAlgorithm;
57
import org.gvsig.lrs.lib.api.LrsAlgorithmParams;
58
import org.gvsig.lrs.lib.api.LrsCreateRouteAlgorithmParams;
59
import org.gvsig.lrs.lib.api.LrsGenerateDynamicSegmentationAlgorithmParams;
60
import org.gvsig.lrs.lib.api.exceptions.LrsCreateRouteException;
61
import org.gvsig.lrs.lib.api.exceptions.LrsException;
62
import org.gvsig.tools.ToolsLocator;
63
import org.gvsig.tools.dataTypes.DataType;
64
import org.gvsig.tools.exception.BaseException;
65
import org.gvsig.tools.i18n.I18nManager;
66
import org.gvsig.tools.locator.LocatorException;
67
import org.gvsig.tools.service.Manager;
68
import org.gvsig.tools.task.SimpleTaskStatus;
69
import org.gvsig.tools.util.HasAFile;
70
import org.gvsig.tools.visitor.VisitCanceledException;
71
import org.gvsig.tools.visitor.Visitor;
72

  
73
/**
74
 * @author fdiaz
75
 *
76
 */
77
public class LrsGenerateDynamicSegmentationAlgorithm implements LrsAlgorithm {
78

  
79
    private static final Logger logger = LoggerFactory.getLogger(LrsGenerateDynamicSegmentationAlgorithm.class);
80

  
81
    private LrsGenerateDynamicSegmentationAlgorithmParams parameters;
82

  
83

  
84
    /**
85
     *
86
     */
87
    public LrsGenerateDynamicSegmentationAlgorithm(LrsGenerateDynamicSegmentationAlgorithmParams parameters) {
88
        this.parameters = parameters;
89

  
90
    }
91

  
92
    /*
93
     * (non-Javadoc)
94
     *
95
     * @see org.gvsig.tools.service.Service#getManager()
96
     */
97
    public Manager getManager() {
98
        return null;
99
    }
100

  
101
    /*
102
     * (non-Javadoc)
103
     *
104
     * @see org.gvsig.lrs.lib.api.LrsAlgorithm#getParams()
105
     */
106
    public  LrsAlgorithmParams getParams() {
107
        return this.parameters;
108
    }
109

  
110
    /*
111
     * (non-Javadoc)
112
     * @see org.gvsig.lrs.lib.api.LrsAlgorithm#execute(org.gvsig.tools.task.SimpleTaskStatus)
113
     */
114
    public void execute(final SimpleTaskStatus taskStatus) throws LrsException {
115
        NewFeatureStoreParameters newFeatureStoreParameters = parameters.getNewFeatureStoreParameters();
116
        final FeatureStore sourceFeatureStore = parameters.getSourceFeatureStore();
117
        final FeatureAttributeDescriptor idRouteField = parameters.getIdRouteField();
118
        final FeatureAttributeDescriptor idTableRouteField = parameters.getValueTableIdRouteField();
119
        FeatureStore tableFeatureStore = parameters.getValueTableFeatureStore();
120
        final FeatureAttributeDescriptor landmarkField = parameters.getLandmarkField();
121
        final FeatureAttributeDescriptor finalLandmarkField = parameters.getFinalLandmarkField();
122
        final FeatureAttributeDescriptor valueField = parameters.getValueField();
123

  
124
        logger.info(parameters.toString());
125

  
126
        taskStatus.setTitle(parameters.getName());
127
        I18nManager i18nManager = ToolsLocator.getI18nManager();
128
        taskStatus.message(i18nManager.getTranslation("processing"));
129

  
130
        try {
131
            final String tableRouteFieldName=idTableRouteField.getName();
132
            final String fromFieldName;
133
            final DataType fromDataType;
134
            final String toFieldName;
135
            final DataType toDataType;
136
            final int geomType;
137
            if (landmarkField!=null){
138
                fromDataType=landmarkField.getDataType();
139
                if (finalLandmarkField!=null){
140
                    fromFieldName="PK INICIAL";
141
                    toFieldName="PK FINAL";
142
                    toDataType=finalLandmarkField.getDataType();
143
                    geomType = Geometry.TYPES.MULTILINE;
144
                }else{
145
                    fromFieldName="PK";
146
                    toFieldName=null;
147
                    toDataType=null;
148
                    geomType = Geometry.TYPES.POINT;
149
                }
150
            }else{
151
                //TODO: Si no hay fromFieldName ?salir por patas?
152
                fromFieldName=null;
153
                fromDataType=null;
154
                toFieldName=null;
155
                toDataType=null;
156
                geomType = Geometry.TYPES.POINT;
157
            }
158

  
159
            final FeatureStore newFeatureStore = createNewDataStore(
160
                newFeatureStoreParameters,
161
                idRouteField,
162
                fromFieldName,
163
                toFieldName,
164
                valueField,
165
                geomType
166
             );
167

  
168
            FeatureSet tableFeatures;
169
            tableFeatures=tableFeatureStore.getFeatureSet();
170
            taskStatus.setRangeOfValues(0, tableFeatures.getSize()-1);
171
            newFeatureStore.edit(FeatureStore.MODE_FULLEDIT);
172

  
173
            tableFeatures.accept(new Visitor() {
174

  
175
                int taskCount=0;
176
                public void visit(Object obj) throws VisitCanceledException, BaseException {
177
                    Feature feature = (Feature) obj;
178
                    String routeName = (String) feature.get(tableRouteFieldName);
179
                    Object objFrom = null;
180
                    Object objTo = null;
181
                    if (fromFieldName != null) {
182
                        objFrom = feature.get(landmarkField.getName());
183
                        double fromValue = LrsAlgorithmUtils.getAsDouble(objFrom, fromDataType);
184
                        Object value = feature.get(valueField.getName());
185
                        if (toFieldName == null || toFieldName.isEmpty()) {
186
                            addSegmentatePointsFeatures(newFeatureStore, sourceFeatureStore, idRouteField, routeName, fromFieldName, fromValue, valueField, value);
187
                        } else {
188
                            objTo = feature.get(finalLandmarkField.getName());
189
                            double toValue = LrsAlgorithmUtils.getAsDouble(objTo, toDataType);
190
                            addSegmentateLinesFeatures(newFeatureStore, sourceFeatureStore, idRouteField, routeName,
191
                                fromFieldName, fromValue, toFieldName, toValue, valueField, value);
192
                        }
193

  
194
                    } else {
195
                        //TODO: ?Exception?
196
                    }
197
                    taskStatus.setCurValue(taskCount++);
198
                }
199

  
200
                private void addSegmentatePointsFeatures(final FeatureStore featureStore,
201
                    FeatureStore sourceFeatureStore, final FeatureAttributeDescriptor idRouteField,
202
                    final String routeName, final String fromFieldName, final double fromValue, final FeatureAttributeDescriptor valueField, final Object value)
203
                    throws LocatorException, BaseException {
204

  
205
                    DataManager dataManager = DALLocator.getDataManager();
206
                    FeatureQuery query = sourceFeatureStore.createFeatureQuery();
207
                    String expression = StringUtils.replace(StringUtils.replace("NOMBRE = 'a%'", "NOMBRE", idRouteField.getName()), "a%", routeName);
208
                    query.setFilter( dataManager.createExpresion(expression) );
209

  
210
                    FeatureSet features = sourceFeatureStore.getFeatureSet(query);
211
                    features.accept(new Visitor() {
212

  
213
                        public void visit(Object obj) throws VisitCanceledException, BaseException {
214
                            Feature feature = (Feature)obj;
215
                            Geometry geom = feature.getDefaultGeometry();
216
                            List<Point>points = LrsAlgorithmUtils.getPointsWithM(geom, fromValue);
217
                            for (Iterator<Point> iterator = points.iterator(); iterator.hasNext();) {
218
                                Point point = (Point) iterator.next();
219
                                EditableFeature newFeature = featureStore.createNewFeature(true);
220
                                newFeature.set(idRouteField.getName(), routeName);
221
                                newFeature.set(fromFieldName, fromValue);
222
                                newFeature.set(valueField.getName(), value);
223
                                newFeature.setDefaultGeometry(point);
224
                                featureStore.insert(newFeature);
225
                            }
226
                        }
227
                    });
228
                }
229

  
230
                private void addSegmentateLinesFeatures(final FeatureStore featureStore,
231
                    FeatureStore sourceFeatureStore, final FeatureAttributeDescriptor idRouteField,
232
                    final String routeName, final String fromFieldName, final double fromValue,
233
                    final String toFieldName, final double toValue, final FeatureAttributeDescriptor valueField, final Object value) throws LocatorException, BaseException {
234

  
235
                    DataManager dataManager = DALLocator.getDataManager();
236
                    FeatureQuery query = sourceFeatureStore.createFeatureQuery();
237
                    String expression = StringUtils.replace(StringUtils.replace("NOMBRE = 'a%'", "NOMBRE", idRouteField.getName()), "a%", routeName);
238
                    query.setFilter( dataManager.createExpresion(expression) );
239

  
240
                    FeatureSet features = sourceFeatureStore.getFeatureSet(query);
241
                    features.accept(new Visitor() {
242

  
243
                        public void visit(Object obj) throws VisitCanceledException, BaseException {
244
                            Feature feature = (Feature) obj;
245
                            Geometry geom = feature.getDefaultGeometry();
246
                            MultiLine lines = LrsAlgorithmUtils.getLinesBetweenTwoM(geom, fromValue, toValue);
247
                            if (lines != null && lines.getPrimitivesNumber()>0) {
248
                                EditableFeature newFeature = featureStore.createNewFeature(true);
249
                                newFeature.set(idRouteField.getName(), routeName);
250
                                newFeature.set(fromFieldName, fromValue);
251
                                newFeature.set(toFieldName, toValue);
252
                                newFeature.set(valueField.getName(), value);
253
                                newFeature.setDefaultGeometry(lines);
254
                                featureStore.insert(newFeature);
255
                            }
256
                        }
257
                    });
258
                }
259
            });
260

  
261
            newFeatureStore.finishEditing();
262

  
263
        } catch (Exception e1) {
264
            taskStatus.abort();
265
            throw new LrsCreateRouteException("Error creating routes", e1);
266
        }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff