Revision 8028

View differences:

trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/AbstractNetSolver.java
62 62
	 */
63 63
	protected FLyrVect lyrVect;
64 64
	protected IGraph graph;
65
	protected ArrayList flags;
65
	protected ArrayList flags = new ArrayList();
66 66
	
67 67
	
68 68
//	private GvNode findNode(double x, double y)
......
161 161
	}
162 162

  
163 163
	/**
164
	 * TODO:
164
	 * TODO: Por ahora, cogemos el nodo m?s cercano. Lo correcto
165
	 * es a?adir un nuevo nodo que divida el arco, y devolver el 
166
	 * id de ese nodo.
165 167
	 * @param flag
166 168
	 * @return
167 169
	 */
168 170
	protected int creaArcosVirtuales(GvFlag flag) {
169
		
170
		return -1;
171
		GvEdge edge = graph.getEdgeByID(flag.getIdArc());
172
		GvNode from = graph.getNodeByID(edge.getIdNodeOrig());
173
		GvNode to = graph.getNodeByID(edge.getIdNodeEnd());
174
		if (flag.getPct() > 0.5)
175
			return to.getIdNode();
176
		else
177
			return from.getIdNode();
171 178
	}
172 179
	
180
	/**
181
	 * @param idArc
182
	 * @param x
183
	 * @param y
184
	 * @return entre 0.0 y 1.0
185
	 */
173 186
	private double percentAlong(long idArc, double x, double y)
174 187
	{
175 188
		return 0;
......
183 196
		int idArc = findClosestArc(x, y, tol);
184 197
		GvFlag flag = new GvFlag();
185 198
		flag.setIdArc(idArc);
199
		flag.setPct(percentAlong(idArc, x, y));
186 200
		flag.setDirec(flagDirection);
187 201
		flag.setIdFlag(flags.size());
188 202
		return flag;		
......
196 210
		GvFlag flag = new GvFlag();
197 211
		flag.setIdArc(idArc);
198 212
		flag.setDirec(GvFlag.BOTH_DIRECTIONS);
213
		flag.setPct(percentAlong(idArc, x, y));
199 214
		flag.setIdFlag(flags.size());
215
		flags.add(flag);
200 216
		return flag;
201 217
	}
202 218

  
......
215 231
		return lyrVect;
216 232
	}
217 233

  
218
	public void loadNetwork(INetworkLoader loader) {
219
		graph = loader.loadNetwork();
220
	}
221

  
222 234
	public IGraph getGraph() {
223 235
		return graph;
224 236
	}
237
	
238
	public void setGraph(IGraph g) {
239
		this.graph  = g;		
240
	}
225 241

  
242

  
226 243
	public void setLyrVect(FLyrVect lyrVect) {
227 244
		this.lyrVect = lyrVect;
228 245
	}
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/NetworkRedLoader.java
126 126
			long t2 = System.currentTimeMillis();
127 127
			System.out.println("Tiempo de carga: " + (t2-t1) + " msecs");
128 128
			System.out.println("NumEdges = " + g.getNumEdges());
129
			return g;
129 130
			} catch (FileNotFoundException e) {
130 131
				// TODO Auto-generated catch block
131 132
				e.printStackTrace();
......
230 231
		// Distance
231 232
		// TODO: PONERLO COMO DOUBLE DENTRO DEL FICHERO!!!!
232 233
		edge.setDistance(buf.getFloat());
234
		// TODO: POR AHORA, WEIGHT = LENGTH. Con setVelocities() lo cambiamos.		
235
		edge.setWeight(edge.getDistance());
236
		
233 237
//		memcpy(&Arcos[link_num].Coste2,puntero,sizeof(float));
234 238

  
235 239
//		pNodo1 = &Nodos[node_num1];
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/GvNode.java
50 50
	private double x;
51 51
	private double y;
52 52
	
53
	long from_link = -1; // id del Arco desde el que hemos llegado
53
	int from_link = -1; // id del Arco desde el que hemos llegado
54 54
	int   numSoluc = 0; // Empezamos con esto a cero en toda la red. 
55 55
					// De manera global, habr? una variable numSolucGlobal que indica el n? de cada petici?n de ruta.
56 56
					// Sirve para no tener que inicializar siempre tooooda la red. Lo que hacemos es comparar el 
......
109 109
	public void setEstimacion(double estimacion) {
110 110
		this.estimacion = estimacion;
111 111
	}
112
	public long getFromLink() {
112
	public int getFromLink() {
113 113
		return from_link;
114 114
	}
115
	public void setFromLink(long from_link) {
115
	public void setFromLink(int from_link) {
116 116
		this.from_link = from_link;
117 117
	}
118 118
	public ArrayList getTurns() {
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/NetworkWriter.java
45 45
import java.io.IOException;
46 46
import java.io.RandomAccessFile;
47 47
import java.nio.ByteOrder;
48
import java.nio.MappedByteBuffer;
49
import java.nio.channels.FileChannel;
50
import java.nio.channels.FileChannel.MapMode;
51 48
import java.sql.Types;
49
import java.util.ArrayList;
52 50
import java.util.Collection;
53 51
import java.util.Hashtable;
54 52
import java.util.Iterator;
......
378 376
		// PARA SABER SI EST? M?S CERCA DE UN NODO O DEL OTRO.
379 377

  
380 378
		Hashtable nodeHash = new Hashtable();
379
		ArrayList nodes = new ArrayList();
381 380

  
382 381
		try {
383 382
			if (lyrSrc.getShapeType() != FShape.LINE) {
......
443 442
					idNodo1 = nodeCount++;
444 443
					nodeAux = new NodeGv(c1, idNodo1);
445 444
					nodeHash.put(c1, nodeAux);
445
					nodes.add(nodeAux);
446 446
				} else {
447 447
					nodeAux = (NodeGv) nodeHash.get(c1);
448 448
				}
......
453 453
					idNodo2 = nodeCount++;
454 454
					nodeAux = new NodeGv(c2, idNodo2);
455 455
					nodeHash.put(c2, nodeAux);
456
					nodes.add(nodeAux);
456 457

  
457 458
				} else {
458 459
					nodeAux = (NodeGv) nodeHash.get(c2);
......
508 509

  
509 510
			}
510 511

  
511
			int numNodos = nodeHash.size();
512 512

  
513
			Collection nodes = nodeHash.values();
514
			Iterator it = nodes.iterator();
515

  
516
			while (it.hasNext()) {
517
				NodeGv node = (NodeGv) it.next();
513
			for (int j=0; j < nodes.size(); j++) {
514
				NodeGv node = (NodeGv) nodes.get(j);
518 515
				output.writeInt(node.getId().intValue());
519 516
				output.writeDouble(node.getCoordinate().x);
520 517
				output.writeDouble(node.getCoordinate().y);
......
524 521
			// buf.position(0);
525 522
			output.writeInt(numTramos);
526 523
			output.writeInt(edgeCount);
527
			output.writeInt(numNodos);
524
			output.writeInt(nodes.size());
528 525

  
529 526
			// buf.force();
530 527
			output.close();
531 528
			file.close();
532 529

  
533
			numNodos = 0;
534 530
			return 0;
535 531
		} catch (DriverIOException e) {
536 532
			e.printStackTrace();
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/INetSolver.java
51 51

  
52 52
	public ArrayList getFlags();
53 53
	
54
	public void loadNetwork(INetworkLoader loader);
54
	public void setGraph(IGraph g);
55
	
56
	public IGraph getGraph();
55 57

  
56 58
}
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/solvers/Route.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.graph.solvers;
42

  
43
import java.util.ArrayList;
44

  
45
import com.hardcode.gdbms.engine.values.DoubleValue;
46
import com.hardcode.gdbms.engine.values.Value;
47
import com.hardcode.gdbms.engine.values.ValueFactory;
48
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
49
import com.iver.cit.gvsig.fmap.core.IFeature;
50
import com.iver.cit.gvsig.fmap.core.IGeometry;
51

  
52
/**
53
 * @author fjp
54
 * featureList es un array de IFeature.
55
 * Los campos que tiene cada feature son:
56
 * 0-> Id_Tramo (idArc sobre el que est? ese tramo de ruta.
57
 * 1-> Weight
58
 * 2-> Length
59
 * 3-> Texto calle o via por la que pasa.
60
 *
61
 */
62
public class Route {
63
	
64
	public IFeature addRouteFeature(IGeometry geom, int idArc, double weight, double length, String text)
65
	{
66
		Value[] values = new Value[4];
67
		values[0] = ValueFactory.createValue(idArc);
68
		values[1] = ValueFactory.createValue(weight);
69
		values[2] = ValueFactory.createValue(length);
70
		values[3] = ValueFactory.createValue(text);
71
		System.out.println("A?ado text= " + text);
72
		DefaultFeature feat = new DefaultFeature(geom, values, featureList.size() + "");
73
		featureList.add(feat);
74
		return feat;
75
	}
76
	private ArrayList featureList = new ArrayList();
77
	
78
	private ArrayList getFeatureList() 
79
	{
80
		return featureList;
81
	}
82
	
83
	public String getInstructions() {
84
		return null;
85
	}
86
	
87
	public double getLength() {
88
		double  distTotal = 0;
89
		for (int i=0; i < featureList.size(); i++)
90
		{
91
			IFeature feat = (IFeature) featureList.get(i);
92
			DoubleValue length = (DoubleValue) feat.getAttribute(2);
93
			double dist = length.doubleValue();
94
			distTotal += dist;
95
		}
96
		return distTotal;
97
	}
98
	
99
	public double getCost() {
100
		double  costTotal = 0;
101
		for (int i=0; i < featureList.size(); i++)
102
		{
103
			IFeature feat = (IFeature) featureList.get(i);
104
			DoubleValue costVal = (DoubleValue) feat.getAttribute(1);
105
			double cost = costVal.doubleValue();
106
			costTotal += cost;
107
		}
108
		return costTotal;		
109
	}
110
}
111

  
112

  
0 113

  
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/solvers/ShortestPathSolver.java
41 41
package com.iver.cit.gvsig.graph.solvers;
42 42

  
43 43
import java.util.ArrayList;
44
import java.util.Vector;
44 45

  
46
import com.iver.cit.gvsig.fmap.DriverException;
47
import com.iver.cit.gvsig.fmap.core.IFeature;
48
import com.iver.cit.gvsig.fmap.core.IGeometry;
49
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
50
import com.iver.cit.gvsig.graph.GraphException;
45 51
import com.iver.cit.gvsig.graph.core.AbstractNetSolver;
46 52
import com.iver.cit.gvsig.graph.core.GvEdge;
47 53
import com.iver.cit.gvsig.graph.core.GvFlag;
48 54
import com.iver.cit.gvsig.graph.core.GvNode;
55
import com.iver.cit.gvsig.graph.core.IGraph;
49 56

  
50 57
public class ShortestPathSolver extends AbstractNetSolver {
58
	
59
	protected Route route = new Route();
60
	private int fieldIndexStreetName;
61
	
62
	public void setFielStreetName(String name) {
63
		try {
64
			int aux = lyrVect.getRecordset().getFieldIndexByName(name);
65
			if (aux == -1)
66
				throw new RuntimeException("Field " + name + " not found.");
67
			fieldIndexStreetName = aux;
68
		} catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
69
			// TODO Auto-generated catch block
70
			e.printStackTrace();
71
		} catch (DriverException e) {
72
			// TODO Auto-generated catch block
73
			e.printStackTrace();
74
		}
75
		
76
	}
51 77

  
52 78
	/**
53 79
	 * @return a list of features
80
	 * @throws GraphException 
54 81
	 */
55
	public ArrayList calculateRoute() {
82
	public Route calculateRoute() throws GraphException {
56 83
		if (flags.size() == 0)
57 84
			throw new RuntimeException("Please, add flags before");
58 85
		int desde = 0;
......
72 99
				// idT2=%ld",desde,hasta,newCost, idTramos[desde],
73 100
				// idTramos[hasta]);
74 101
				// MessageBox(NULL,Msg,"CalculaRuta",MB_OK);
75

  
102
				try {
103
					populateRoute(idStart, idStop);
104
				} catch (DriverException e) {
105
					e.printStackTrace();
106
					throw new GraphException(e);
107
				}
76 108
				// NUEVO: 18/8/2003
77 109
				// if (newCost != INFINITO)
78 110
				// {
......
102 134
			hasta++;
103 135
		}
104 136

  
105
		return null;
137
		return route;
106 138
	}
107 139

  
140
	private void populateRoute(int idStart, int idEnd) throws DriverException {
141
		int idEnlace;
142
		GvNode node;
143
		GvEdge link;
144
		double costeEntrada;
145

  
146
		// Trazar el camino desde idEnd hasta idStart hacia atr?s marcando los Enlaces
147
		double Coste = 0;
148
		double Coste2 = 0;
149
		node = graph.getNodeByID(idEnd);
150
		int from_link = node.getFromLink();
151
		VectorialAdapter va = (VectorialAdapter) lyrVect.getSource();
152
		while (node.getIdNode() != idStart)
153
		{
154
			idEnlace = from_link;
155
			if (idEnlace == -1)
156
			{
157
				throw new RuntimeException("Fallo al recorrer de manera inversa la soluci?n. Encontrado arco con -1");
158
				// break; // FALLO!!
159
			} 
160
			link = graph.getEdgeByID(idEnlace);
161
			IFeature feat = va.getFeature(link.getIdArc());
162
			route.addRouteFeature(feat.getGeometry(), link.getIdArc(), 
163
					link.getWeight(), link.getDistance(), feat.getAttribute(getFieldIndexStreetName()).toString());
164

  
165
			node = graph.getNodeByID(link.getIdNodeOrig());
166

  
167
			Coste = Coste + link.getWeight();
168
			Coste2 = Coste2 + link.getDistance();
169

  
170
			// TODO:
171
			// from_link = node.get_from_link(idEnlace, &costeEntrada);
172
			from_link = node.getFromLink();
173
			
174
	    }	
175
	}
176

  
177
	private int getFieldIndexStreetName() {
178
		return fieldIndexStreetName;
179
	}
180

  
108 181
	private double dijkstra(int idStart, int idStop) {
109 182
		int nodeNum;
110 183
		int linkNum;
......
160 233
		while ((!bExit) && (candidatos.size() > 0)) {
161 234
			// Buscamos el nodo con m?nimo coste
162 235
			node = (GvNode) candidatos.get(0);
236
			bestNode = node;
163 237
			bestCost = node.getBestCost();
164 238
			for (nodeNum = 1; nodeNum < candidatos.size(); nodeNum++) {
165 239
				node = (GvNode) candidatos.get(nodeNum);
......
173 247
			// Borramos el mejor nodo de la lista de candidatosSTL
174 248
			node.setStatus(GvNode.statWasInList);
175 249
			candidatos.remove(node);
250
			// System.out.println("LINK " + link.getIdArc() + " from ");
251
			System.out.println("from " + idStart + " to " + finalNode.getIdNode() + ". node=" + node.getIdNode());
176 252
			// Miramos si hemos llegado donde quer?amos
177 253
			if (bestNode.getIdNode() == idStop) {
178 254
				bExit = true;
......
261 337
						// Es una mejora, as? que actualizamos el vecino y
262 338
						// lo a?adimos a los candidatosSTL
263 339
						toNode.setBestCost(newCost);
340
						OJO: ESTO EST? MAL. NO ES IDARC, SINO IDEDGE CON LO QUE HAY QUE TRABAJAR AQUI.
341
						 
264 342
						toNode.setFromLink(link.getIdArc());
265 343

  
266 344
						if (toNode.getStatus() != GvNode.statNowInList) {
......
277 355

  
278 356
		return newCost;
279 357
	}
358

  
280 359
}
trunk/extensions/extGraph_predes/src/com/iver/cit/gvsig/graphtests/TestLoader.java
41 41
package com.iver.cit.gvsig.graphtests;
42 42

  
43 43
import java.io.File;
44
import java.util.ArrayList;
44 45

  
46
import org.cresques.cts.IProjection;
47

  
45 48
import junit.framework.TestCase;
46 49

  
47 50
import com.hardcode.driverManager.Driver;
......
55 58
import com.hardcode.gdbms.engine.data.driver.DriverException;
56 59
import com.hardcode.gdbms.engine.data.driver.FileDriver;
57 60
import com.hardcode.gdbms.engine.data.driver.ObjectDriver;
61
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
62
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
58 63
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
59 64
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
65
import com.iver.cit.gvsig.graph.GraphException;
60 66
import com.iver.cit.gvsig.graph.core.EdgeWeightLabeller;
67
import com.iver.cit.gvsig.graph.core.IGraph;
61 68
import com.iver.cit.gvsig.graph.core.NetworkLoader;
62 69
import com.iver.cit.gvsig.graph.core.NetworkRedLoader;
70
import com.iver.cit.gvsig.graph.solvers.Route;
71
import com.iver.cit.gvsig.graph.solvers.ShortestPathSolver;
63 72

  
64 73
import edu.uci.ics.jung.algorithms.shortestpath.DijkstraDistance;
65 74
import edu.uci.ics.jung.graph.ArchetypeVertex;
......
67 76

  
68 77
public class TestLoader extends TestCase {
69 78
	DataSourceFactory dsf;
79
	FLyrVect lyr;
70 80
	
71 81
	
72 82
	public void testLoadRedNetwork() {
73 83
		NetworkRedLoader netLoader = new NetworkRedLoader();
74
		netLoader.loadNetwork();
84
		IGraph g = netLoader.loadNetwork();
75 85
		netLoader.loadJungNetwork();
86
		
87
		// Probamos la algoritmia: distancia entre nodo 1 y nodo 1000
88
		ShortestPathSolver solver = new ShortestPathSolver();
89
		solver.setLyrVect(lyr);
90
		solver.setGraph(g);
91
		
92
		// Primer punto
93
		solver.addFlag(443739.3, 4474704, 10);
94
		
95
		// Segundo punto
96
		solver.addFlag(443202.4, 4478132, 10);
97
		long t1 = System.currentTimeMillis();
98
		Route resul;
99
		try {
100
			solver.setFielStreetName("Nombre");
101
			resul = solver.calculateRoute();
102
			long t2 = System.currentTimeMillis();
103
			
104
//			assertEquals(dist.doubleValue(), 8887, 0);
105
			
106
			System.out.println("dist =" + resul.getLength() + " meters. msecs: " + (t2-t1));
107
			
108
		} catch (GraphException e) {
109
			// TODO Auto-generated catch block
110
			e.printStackTrace();
111
		}
112
		
76 113
	}
77 114
	
78 115
	/*
......
140 177
				}
141 178
			});
142 179
		dm.loadDrivers(new File("../_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers"));
180
		LayerFactory.setDriversPath("../_fwAndami/gvSIG/extensiones/com.iver.cit.gvsig/drivers");
143 181

  
144 182
		//Setup del factory de DataSources
145 183
        dsf = LayerFactory.getDataSourceFactory();
......
148 186
		//Setup de las tablas
149 187
		dsf.addFileDataSource("gdbms dbf driver", "nodes", "c:/nodes.dbf");
150 188
		dsf.addFileDataSource("gdbms dbf driver", "edges", "c:/edges.dbf");
189
		
190
		IProjection prj = CRSFactory.getCRS("EPSG:23030");
191
		File shpFile = new File("c:/ejes.shp");
192
		lyr = (FLyrVect) LayerFactory.createLayer("Ejes",
193
				"gvSIG shp driver", shpFile, prj);
194
		
151 195

  
152 196
	}
153 197

  

Also available in: Unified diff