diff --git a/.gitignore b/.gitignore index 32a4bd9..2c4b80d 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ null *.aux *.synctex* bin +core/.RData diff --git a/core/db.properties b/core/db.properties new file mode 100644 index 0000000..982641b --- /dev/null +++ b/core/db.properties @@ -0,0 +1,11 @@ +# remoto - nuvem arida +driver=org.postgresql.Driver +host=jdbc:postgresql://177.130.199.157:8080/fortaleza +user=postgres +password=aridapostgres12 + +#local +#driver=org.postgresql.Driver +#host=jdbc:postgresql://localhost:5432/fortaleza_novo +#user=postgres +#password=postgres \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml old mode 100755 new mode 100644 index eebefb1..b4a85ec --- a/core/pom.xml +++ b/core/pom.xml @@ -15,29 +15,29 @@ http://arida.github.io/maven-repo/ - + - - GNU Lesser General Public License (LGPL), Version 2.1 - http://www.fsf.org/licensing/licenses/lgpl.txt - repo - - + + GNU Lesser General Public License (LGPL), Version 2.1 + http://www.fsf.org/licensing/licenses/lgpl.txt + repo + + - scm:git:git://github.com/ARiDa/graphast.git - https://github.com/ARiDa/graphast.git - https://github.com/ARiDa/graphast.git + scm:git:git://github.com/ARiDa/graphast.git + https://github.com/ARiDa/graphast.git + https://github.com/ARiDa/graphast.git graphast Graphast - + - - + + UTF-8 @@ -71,15 +71,57 @@ osmpoispbf 1.1 - + com.github.davidmoten rtree 0.7.1 - + + com.github.jbytecode + RCaller + 2.8 + + + + com.github.jbytecode + RCaller + 2.8 + + + + postgresql + postgresql + 9.1-901-1.jdbc4 + + + + org.postgis + postgis-jdbc + 1.3.3 + + + + org.apache.commons + commons-lang3 + 3.4 + + + + org.json + json + 20160212 + + + + + com.github.jbytecode + RCaller + 2.8 + + @@ -126,21 +168,28 @@ - - + + + org.apache.maven.plugins + maven-shade-plugin + 2.4.2 + + + package + + shade + + + + + org.graphast.query.rnn.CompareRNNSearchsMethodsAnalysis + + + + + + + diff --git a/core/src/main/java/org/graphast/importer/CostGenerator.java b/core/src/main/java/org/graphast/importer/CostGenerator.java index 710b5af..c29c217 100644 --- a/core/src/main/java/org/graphast/importer/CostGenerator.java +++ b/core/src/main/java/org/graphast/importer/CostGenerator.java @@ -1,105 +1,116 @@ -package org.graphast.importer; - -import java.util.Random; - -import org.graphast.model.Graph; - -public class CostGenerator { - - public static int[] generateSyntheticEdgesCosts(int distance) { - - Random random = new Random(); - - int minSpeed, maxSpeed; - int[] syntheticCosts = new int[96]; - - for(int i=0; i<24; i++) { - minSpeed = 14; - maxSpeed = 17; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=24; i<28; i++) { - minSpeed = 6; - maxSpeed = 9; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=28; i<36; i++) { - minSpeed = 1; - maxSpeed = 4; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=36; i<44; i++) { - minSpeed = 6; - maxSpeed = 9; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=44; i<56; i++) { - minSpeed = 1; - maxSpeed = 4; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=56; i<64; i++) { - minSpeed = 14; - maxSpeed = 17; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=64; i<68; i++) { - minSpeed = 6; - maxSpeed = 9; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=68; i<80; i++) { - minSpeed = 1; - maxSpeed = 4; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=80; i<88; i++) { - minSpeed = 6; - maxSpeed = 9; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - for(int i=88; i<96; i++) { - minSpeed = 14; - maxSpeed = 17; - - syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); - - } - - return syntheticCosts; - } - - public static void generateAllSyntheticEdgesCosts(Graph graph) { - for (int i = 0; i < graph.getNumberOfEdges(); i++) { - graph.setEdgeCosts(i, CostGenerator.generateSyntheticEdgesCosts(graph.getEdge(i).getDistance())); - } - } - +package org.graphast.importer; + +import java.util.Random; + +import org.graphast.model.Graph; + + +public class CostGenerator { + + public static int[] generateSyntheticEdgesCosts(int distance) { + + Random random = new Random(); + + int minSpeed, maxSpeed; //Millimeters Per Millisecond (mm/ms) + int[] syntheticCosts = new int[96]; + + //1:00h to 6:00h + for(int i=0; i<24; i++) { + minSpeed = 14; // 50km/h + maxSpeed = 17; // 60km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //6:00h to 7:00h + for(int i=24; i<28; i++) { + minSpeed = 6; //21km/h + maxSpeed = 9; //32km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //7:00h to 9:00h + for(int i=28; i<36; i++) { + minSpeed = 1; //3km/h + maxSpeed = 4; //14km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //9:00h to 11:00h + for(int i=36; i<44; i++) { + minSpeed = 6; //21km/h + maxSpeed = 9; //32km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //11:00h to 14:00h + for(int i=44; i<56; i++) { + minSpeed = 1; //3km/h + maxSpeed = 4; //14km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //14:00h to 16:00h + for(int i=56; i<64; i++) { + minSpeed = 14; //50km/h + maxSpeed = 17; //60km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //16:00h to 17:00h + for(int i=64; i<68; i++) { + minSpeed = 6; //21km/h + maxSpeed = 9; //30/km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //17:00h to 20:00h + for(int i=68; i<80; i++) { + minSpeed = 1; //3km/h + maxSpeed = 4; //14km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //20:00h to 22:00h + for(int i=80; i<88; i++) { + minSpeed = 6; //21km/h + maxSpeed = 9; //30/km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + //22:00h to 00:00h + for(int i=88; i<96; i++) { + minSpeed = 14; //50km/h + maxSpeed = 17; //60km/h + + syntheticCosts[i] = distance/(random.nextInt(maxSpeed-minSpeed)+minSpeed); + + } + + return syntheticCosts; + } + + public static void generateAllSyntheticEdgesCosts(Graph graph) { + for (int i = 0; i < graph.getNumberOfEdges(); i++) { + graph.setEdgeCosts(i, CostGenerator.generateSyntheticEdgesCosts(graph.getEdge(i).getDistance())); + } + } + } \ No newline at end of file diff --git a/core/src/main/java/org/graphast/importer/GraphGeneratorGrid.java b/core/src/main/java/org/graphast/importer/GraphGeneratorGrid.java new file mode 100644 index 0000000..8c9422e --- /dev/null +++ b/core/src/main/java/org/graphast/importer/GraphGeneratorGrid.java @@ -0,0 +1,136 @@ +package org.graphast.importer; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +import org.graphast.model.Edge; +import org.graphast.model.EdgeImpl; +import org.graphast.model.GraphBounds; +import org.graphast.model.GraphImpl; +import org.graphast.model.Node; +import org.graphast.model.NodeImpl; + +public class GraphGeneratorGrid { + + private int width; + private int length; + private GraphBounds graph; + private double percentagemPoi; + private BigDecimal distance_largura; + private BigDecimal distance_altura; + + public GraphGeneratorGrid(String pathGraph, int width, int length, double percentualPoi) { + this.width = width; + this.length = length; + this.percentagemPoi = percentualPoi; + this.graph = new GraphImpl(pathGraph); + } + + public GraphGeneratorGrid(String pathGraph, int size, double percentualPoi) { + this(pathGraph, size, size, percentualPoi); + } + + public void generateGraph() { + plotNodes(); + plotEdges(); + graph.createBounds(); + } + + private void plotNodes() { + + BigDecimal interador_largura = BigDecimal.valueOf(180).divide(BigDecimal.valueOf(width), 8, RoundingMode.HALF_UP); + BigDecimal interador_altura = BigDecimal.valueOf(180).divide(BigDecimal.valueOf(length), 8, RoundingMode.HALF_UP); + this.distance_largura = interador_largura; + this.distance_altura = interador_altura; + + Set listaIdsPoi = getListIdsPois(); + + Integer category = 0; + for (int i = 0; i < width; i++) { + BigDecimal latitude = interador_altura.multiply(BigDecimal.valueOf(i)).add(BigDecimal.valueOf(-90)); + for (int j = 0; j < length; j++) { + BigDecimal longitude = interador_largura.multiply(BigDecimal.valueOf(j)).add(BigDecimal.valueOf(-90));; + Node node = new NodeImpl(Long.valueOf(category), latitude.doubleValue(), longitude.doubleValue()); + if(listaIdsPoi.contains(category)) { + int[] costs = new int[]{0}; + node.setCategory(category); + node.setExternalId(category); + node.setLabel("CATEGORY "+category); + node.setCosts(costs); + listaIdsPoi.remove(category); + } + graph.addNode(node); + category++; + } + } + } + + private Set getListIdsPois() { + + int quantidadeVerticesPoi = BigDecimal.valueOf(width).multiply(BigDecimal.valueOf(length)).multiply(BigDecimal.valueOf(percentagemPoi)).divide(BigDecimal.valueOf(100.0f), 8, RoundingMode.UP).intValue(); + + Set listIdPoi = new HashSet<>(); + do { + int rangeMax = width*length - 1; + Double idRandom = generatePdseurandom(0, rangeMax); + listIdPoi.add(idRandom.intValue()); + } while(listIdPoi.size()> mapTaxi = dao.getPoiTaxiFortaleza(); + + ResultSet result = dao.getPoints(table); + int pointCount = 0; + while (result.next()) { + LineString lineString = new LineString(result.getString(FIELD_LINESTRING)); + Point[] arrayPoints = lineString.getPoints(); + LOGGER.info(String.format("registro: %s", result.getString(FIELD_LINESTRING))); + + + int idRoad = result.getInt(FIELD_ID_LINESTRING); + Node previousNode = null; + + for (Point point : arrayPoints) { + pointCount++; + LOGGER.info( String.format("Point [x,y]: %s,%s", point.getX(), point.getY())); + Node node = new NodeImpl(point.getY(), point.getX()); + node.setLabel(Long.valueOf(idRoad).toString()); + Long nodeId = graph.getNodeId(GeoUtils.latLongToInt(node.getLatitude()), GeoUtils.latLongToInt(node.getLongitude())); + + if (nodeId != null) { + LOGGER.info(String.format("point already exist in graph")); + node = graph.getNode(nodeId); + } else { + graph.addNode(node); + LOGGER.info(String.format("point inserted in graph with ID: %s", node.getId())); + } + + + + if (previousNode != null && !previousNode.getId().equals(node.getId())) { + LOGGER.info( String.format("Add edge from previous: %s to current: %s node", previousNode.getId(), node.getId())); + Edge edge = new EdgeImpl(idRoad, previousNode.getId().longValue(), node.getId().longValue(), 0, String.valueOf(idRoad)); + addCost(edge); + graph.addEdge(edge); + if(mapTaxi.containsKey(idRoad)) { + for(int i=0; i taxiNodes = getCloseTaxi(externalId); + Node nodeTo = graph.getNode(edge.getToNode()); + + for (Node node: taxiNodes) { + + if (!graph.getCategories().contains(node.getCategory())) { + graph.addNode(node); + Edge edgeToNeighbor = new EdgeImpl(node.getId(), nodeTo.getId(), 1); + addCostZero(edgeToNeighbor); + graph.addEdge(edgeToNeighbor); + } + } + } + + private void addCostZero(Edge edge) { + + int[] costs = new int[SIZE_INTERVAL]; + for (int i : costs) { + costs[i] = 2; + } + edge.setCosts(costs); + } + + private List getCloseTaxi(long idLineString) throws ClassNotFoundException, IOException { + + List taxiNodes = new ArrayList(); + try { + PreparedStatement taxiStatement = ConnectionJDBC.getConnection().prepareStatement(QueryPostgis.QUERY_POINT_TAXI); + taxiStatement.setLong(FIELD_PARAMETER_ID_LINESTRING, idLineString); + ResultSet resultSet = taxiStatement.executeQuery(); + + while (resultSet.next()) { + + String string = resultSet.getString(FIELD_POINT_TAXI); + Point point = new Point(string); + Node node = new NodeImpl(resultSet.getInt(FIELD_ID_TAXI), point.getY(), point.getX()); + node.setCategory(resultSet.getInt(FIELD_ID_TAXI)); + node.setExternalId(resultSet.getInt(FIELD_ID_TAXI)); + taxiNodes.add(node); + } + + ConnectionJDBC.getConnection().close(); + + } catch (SQLException e) { + e.printStackTrace(); + } + + return taxiNodes; + } + +} diff --git a/core/src/main/java/org/graphast/model/Graph.java b/core/src/main/java/org/graphast/model/Graph.java index 16422cd..be38d37 100644 --- a/core/src/main/java/org/graphast/model/Graph.java +++ b/core/src/main/java/org/graphast/model/Graph.java @@ -1,23 +1,22 @@ package org.graphast.model; +import it.unimi.dsi.fastutil.ints.IntBigArrayBigList; +import it.unimi.dsi.fastutil.ints.IntSet; +import it.unimi.dsi.fastutil.longs.Long2IntMap; +import it.unimi.dsi.fastutil.longs.LongList; + import java.util.HashMap; import java.util.List; +import java.util.Set; import org.graphast.enums.CompressionType; import org.graphast.enums.TimeType; import org.graphast.geometry.BBox; import org.graphast.geometry.PoI; import org.graphast.geometry.Point; +import org.graphast.piecewise.Function; import org.graphast.util.FileUtils; -import com.github.davidmoten.rtree.RTree; - -import it.unimi.dsi.fastutil.ints.IntBigArrayBigList; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.LongList; - - public interface Graph { /** @@ -210,6 +209,14 @@ public interface Graph { * @return Id of a node */ public Long getNodeId(double latitude, double longitude); + + /** + * This method return a nodeId based on a given absolute latitude and longitude. + * @param latitude latitude that is given + * @param longitude longitude that is given + * @return Id of a node + */ + public Long getNodeId(int latitude, int longitude); /** * This method returns a label of a given node. @@ -345,6 +352,9 @@ public interface Graph { public String getAbsoluteDirectory(); public void setDirectory(String directory); - -} \ No newline at end of file + public Set getPoiIds(); + + public void setFuntionEdge(long edgeId, Function function); +} + diff --git a/core/src/main/java/org/graphast/model/GraphImpl.java b/core/src/main/java/org/graphast/model/GraphImpl.java index 19603a5..053cdac 100644 --- a/core/src/main/java/org/graphast/model/GraphImpl.java +++ b/core/src/main/java/org/graphast/model/GraphImpl.java @@ -2,11 +2,26 @@ import static org.graphast.util.GeoUtils.latLongToDouble; import static org.graphast.util.GeoUtils.latLongToInt; +import it.unimi.dsi.fastutil.BigArrays; +import it.unimi.dsi.fastutil.ints.IntBigArrayBigList; +import it.unimi.dsi.fastutil.ints.IntOpenHashSet; +import it.unimi.dsi.fastutil.ints.IntSet; +import it.unimi.dsi.fastutil.longs.Long2IntMap; +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2LongMap; +import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongArrayList; +import it.unimi.dsi.fastutil.longs.LongList; +import it.unimi.dsi.fastutil.objects.ObjectBigArrayBigList; +import it.unimi.dsi.fastutil.objects.ObjectBigList; +import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Set; import org.graphast.enums.CompressionType; import org.graphast.enums.TimeType; @@ -14,6 +29,7 @@ import org.graphast.geometry.PoI; import org.graphast.geometry.PoICategory; import org.graphast.geometry.Point; +import org.graphast.piecewise.Function; import org.graphast.util.DistanceUtils; import org.graphast.util.FileUtils; import org.slf4j.Logger; @@ -22,22 +38,6 @@ import com.github.davidmoten.rtree.Entry; import com.github.davidmoten.rtree.RTree; import com.github.davidmoten.rtree.geometry.Geometries; -import com.graphhopper.util.StopWatch; - -import it.unimi.dsi.fastutil.BigArrays; -import it.unimi.dsi.fastutil.ints.IntBigArrayBigList; -import it.unimi.dsi.fastutil.ints.IntOpenHashSet; -import it.unimi.dsi.fastutil.ints.IntSet; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2LongMap; -import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongArrayList; -import it.unimi.dsi.fastutil.longs.LongList; -import it.unimi.dsi.fastutil.objects.ObjectBigArrayBigList; -import it.unimi.dsi.fastutil.objects.ObjectBigList; - -import java.io.Serializable; public class GraphImpl implements Graph, GraphBounds, Serializable { @@ -952,7 +952,8 @@ public List getGeometryByGeometryIndex(long geometryIndex) { return listPoints; } - Long getNodeId(int latitude, int longitude) { + @Override + public Long getNodeId(int latitude, int longitude) { Long result = nodeIndex.get(BigArrays.index(latitude, longitude)); @@ -973,7 +974,9 @@ Long getNodeId(int latitude, int longitude) { */ @Override public Long getNodeId(double latitude, double longitude) { - + if(this.getNumberOfNodes()==0) { + return null; + } int lat, lon; lat = latLongToInt(latitude); @@ -1587,6 +1590,12 @@ public void setDirectory(String directory) { this.absoluteDirectory = FileUtils.getAbsolutePath(directory); this.directory = directory; } + + @Override + public void setFuntionEdge(long edgeId, Function function) { + // TODO Auto-generated method stub + + } /* * A partir daqui estão os métodos adicionais vindos da antiga classe GraphBoundsImpl: @@ -1778,4 +1787,17 @@ public void printInternalEdgeRepresentation() { } } + @Override + public Set getPoiIds() { + Set ids = new HashSet<>(); + long max = nodes.size64()/Node.NODE_BLOCKSIZE; + for (long id = 0; id= 0) { + ids.add(id); + } + } + return ids; + } } diff --git a/core/src/main/java/org/graphast/model/NodeImpl.java b/core/src/main/java/org/graphast/model/NodeImpl.java index dd4df9f..2cce3c7 100644 --- a/core/src/main/java/org/graphast/model/NodeImpl.java +++ b/core/src/main/java/org/graphast/model/NodeImpl.java @@ -1,310 +1,310 @@ -package org.graphast.model; - -import static org.graphast.util.GeoUtils.latLongToDouble; -import static org.graphast.util.GeoUtils.latLongToInt; -import it.unimi.dsi.fastutil.BigArrays; - -import org.graphast.exception.GraphastException; - -public class NodeImpl implements Node { - - private Long id; - - private long externalId; - - private int category; - - private int latitude; - - private int longitude; - - private long firstEdge; - - private long labelIndex; - - private long costsIndex; - - private int[] costs; - - private String label; - - public NodeImpl() { - - } - - /** - * This method will construct a FastGraphNode with the latitude and longitude passed. - * IMPORTANT: the latitude and longitude will be rounded to six decimal places. - * @param latitude Node latitude. - * @param longitude Node longitude. - */ - public NodeImpl(double latitude, double longitude) { - setLatitude(latitude); - setLongitude(longitude); - this.firstEdge = -1; - - if(latitude == Integer.MAX_VALUE || longitude==Integer.MAX_VALUE) { - throw new GraphastException("Invalid coordinate"); - } - } - - /** - * This method will construct a FastGraphNode with the latitude, longitude - * externalId, category, firstEdge, labelIndex and costIndex passed. - * IMPORTANT: the latitude and longitude will be rounded to six decimal places. - * - * @param externalId - * @param category - * @param latitude - * @param longitude - * @param firstEdge - * @param labelIndex - * @param costIndex - */ - NodeImpl(long externalId, int category, double latitude, - double longitude, long firstEdge, long labelIndex, long costIndex, int[] costs) { - - this(latitude, longitude); - this.externalId = externalId; - this.category = category; - this.firstEdge = firstEdge; - this.labelIndex = labelIndex; - this.costsIndex = costIndex; - this.costs = costs; - } - - NodeImpl(long externalId, int category, double latitude, - double longitude, long firstEdge, long labelIndex, long costIndex) { - - this(latitude, longitude); - this.externalId = externalId; - this.category = category; - this.firstEdge = firstEdge; - this.labelIndex = labelIndex; - this.costsIndex = costIndex; - } - - /** - * This method will construct a FastGraphNode with the externalId, latitude and longitude passed. - * IMPORTANT: the latitude and longitude will be rounded to six decimal places. - * - * @param externalId Node id used in the dataset from where the data was imported. - * @param latitude Node latitude. - * @param longitude Node longitude. - */ - public NodeImpl(long externalId, double latitude, double longitude) { - - this(latitude, longitude); - this.externalId = externalId; - this.category = -1; - - } - - /** - * This method will construct a FastGraphNode with the externalId, latitude, longitude and - * label passed. - * IMPORTANT: the latitude and longitude will be rounded to six decimal places. - * - * @param externalId Node id used in the dataset from where the data was imported. - * @param latitude Node latitude. - * @param longitude Node longitude. - * @param label Node label. - */ - public NodeImpl(long externalId, double latitude, double longitude, String label) { - - this(externalId, latitude, longitude); - this.label = label; - - } - public NodeImpl(long externalId, double latitude, double longitude, int category) { - - this(externalId, latitude, longitude); - this.category = category; - } - - public NodeImpl(long externalId, double latitude, double longitude, int[] costs) { - - this(externalId, latitude, longitude); - this.costs = costs; - - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#validate() - */ - @Override - public void validate(){ - - if(latitude == 0 && longitude == 0 && firstEdge == 0){ - throw new GraphastException("Invalid vertex"); - } - - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getCategory() - */ - @Override - public int getCategory() { - return category; - } - - @Override - public void setCategory(int category) { - this.category = category; - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getExternalId() - */ - @Override - public long getExternalId() { - return externalId; - } - - int getExternalIdSegment(){ - return BigArrays.segment(externalId); - } - - int getExternalIdOffset(){ - return BigArrays.displacement(externalId); - } - - @Override - public void setExternalId(long externalId) { - this.externalId = externalId; - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getLatitude() - */ - @Override - public double getLatitude() { - return latLongToDouble(latitude); - } - - int getLatitudeConvertedToInt() { - return latitude; - } - - - @Override - public void setLatitude(double latitude) { - this.latitude = latLongToInt(latitude); - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getLongitude() - */ - @Override - public double getLongitude() { - return latLongToDouble(longitude); - } - - int getLongitudeConvertedToInt() { - return longitude; - } - - @Override - public void setLongitude(double longitude) { - this.longitude = latLongToInt(longitude); - } - - int getFirstEdgeSegment(){ - return BigArrays.segment(firstEdge); - } - - int getFirstEdgeOffset(){ - return BigArrays.displacement(firstEdge); - } - - void setFirstEdge(long firstEdge) { - this.firstEdge = firstEdge; - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getId() - */ - @Override - public Long getId() { - return id; - } - - @Override - public void setId(Long id) { - this.id = id; - } - - long getLabelIndex(){ - return labelIndex; - } - - int getLabelIndexSegment(){ - return BigArrays.segment(labelIndex); - } - - int getLabelIndexOffset(){ - return BigArrays.displacement(labelIndex); - } - - void setLabelIndex(long labelIndex) { - this.labelIndex = labelIndex; - } - - int getCostsIndexSegment(){ - return BigArrays.segment(costsIndex); - } - - int getCostsIndexOffset(){ - return BigArrays.displacement(costsIndex); - } - - public long getCostsIndex() { - return costsIndex; - } - - void setCostsIndex(long costIndex) { - this.costsIndex = costIndex; - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#getLabel() - */ - @Override - public String getLabel() { - return label; - } - - @Override - public void setLabel(String label) { - this.label = label; - } - - @Override - public int[] getCosts() { - return costs; - } - - @Override - public void setCosts(int[] costs) { - this.costs = costs; - } - - /* (non-Javadoc) - * @see org.graphast.model.Node#toString() - */ - @Override - public String toString() { - return "FastGraphNode [id=" + id + ", externalId=" + externalId + ", latitude=" + latitude - + ", longitude=" + longitude + ", firstEdge=" + firstEdge + ", label="+ label + "]"; - } - - public boolean equals(Node n) { - if((n.getLatitude() == this.getLatitude() && (n.getLongitude() == this.getLongitude()) - && n.getCategory() == this.getCategory())) { - return true; - } - return false; - } - -} +package org.graphast.model; + +import static org.graphast.util.GeoUtils.latLongToDouble; +import static org.graphast.util.GeoUtils.latLongToInt; +import it.unimi.dsi.fastutil.BigArrays; + +import org.graphast.exception.GraphastException; + +public class NodeImpl implements Node { + + private Long id; + + private long externalId; + + private int category = -1; + + private int latitude; + + private int longitude; + + private long firstEdge; + + private long labelIndex; + + private long costsIndex; + + private int[] costs; + + private String label; + + public NodeImpl() { + + } + + /** + * This method will construct a FastGraphNode with the latitude and longitude passed. + * IMPORTANT: the latitude and longitude will be rounded to six decimal places. + * @param latitude Node latitude. + * @param longitude Node longitude. + */ + public NodeImpl(double latitude, double longitude) { + setLatitude(latitude); + setLongitude(longitude); + this.firstEdge = -1; + + if(latitude == Integer.MAX_VALUE || longitude==Integer.MAX_VALUE) { + throw new GraphastException("Invalid coordinate"); + } + } + + /** + * This method will construct a FastGraphNode with the latitude, longitude + * externalId, category, firstEdge, labelIndex and costIndex passed. + * IMPORTANT: the latitude and longitude will be rounded to six decimal places. + * + * @param externalId + * @param category + * @param latitude + * @param longitude + * @param firstEdge + * @param labelIndex + * @param costIndex + */ + NodeImpl(long externalId, int category, double latitude, + double longitude, long firstEdge, long labelIndex, long costIndex, int[] costs) { + + this(latitude, longitude); + this.externalId = externalId; + this.category = category; + this.firstEdge = firstEdge; + this.labelIndex = labelIndex; + this.costsIndex = costIndex; + this.costs = costs; + } + + NodeImpl(long externalId, int category, double latitude, + double longitude, long firstEdge, long labelIndex, long costIndex) { + + this(latitude, longitude); + this.externalId = externalId; + this.category = category; + this.firstEdge = firstEdge; + this.labelIndex = labelIndex; + this.costsIndex = costIndex; + } + + /** + * This method will construct a FastGraphNode with the externalId, latitude and longitude passed. + * IMPORTANT: the latitude and longitude will be rounded to six decimal places. + * + * @param externalId Node id used in the dataset from where the data was imported. + * @param latitude Node latitude. + * @param longitude Node longitude. + */ + public NodeImpl(long externalId, double latitude, double longitude) { + + this(latitude, longitude); + this.externalId = externalId; + this.category = -1; + + } + + /** + * This method will construct a FastGraphNode with the externalId, latitude, longitude and + * label passed. + * IMPORTANT: the latitude and longitude will be rounded to six decimal places. + * + * @param externalId Node id used in the dataset from where the data was imported. + * @param latitude Node latitude. + * @param longitude Node longitude. + * @param label Node label. + */ + public NodeImpl(long externalId, double latitude, double longitude, String label) { + + this(externalId, latitude, longitude); + this.label = label; + + } + public NodeImpl(long externalId, double latitude, double longitude, int category) { + + this(externalId, latitude, longitude); + this.category = category; + } + + public NodeImpl(long externalId, double latitude, double longitude, int[] costs) { + + this(externalId, latitude, longitude); + this.costs = costs; + + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#validate() + */ + @Override + public void validate(){ + + if(latitude == 0 && longitude == 0 && firstEdge == 0){ + throw new GraphastException("Invalid vertex"); + } + + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getCategory() + */ + @Override + public int getCategory() { + return category; + } + + @Override + public void setCategory(int category) { + this.category = category; + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getExternalId() + */ + @Override + public long getExternalId() { + return externalId; + } + + int getExternalIdSegment(){ + return BigArrays.segment(externalId); + } + + int getExternalIdOffset(){ + return BigArrays.displacement(externalId); + } + + @Override + public void setExternalId(long externalId) { + this.externalId = externalId; + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getLatitude() + */ + @Override + public double getLatitude() { + return latLongToDouble(latitude); + } + + int getLatitudeConvertedToInt() { + return latitude; + } + + + @Override + public void setLatitude(double latitude) { + this.latitude = latLongToInt(latitude); + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getLongitude() + */ + @Override + public double getLongitude() { + return latLongToDouble(longitude); + } + + int getLongitudeConvertedToInt() { + return longitude; + } + + @Override + public void setLongitude(double longitude) { + this.longitude = latLongToInt(longitude); + } + + int getFirstEdgeSegment(){ + return BigArrays.segment(firstEdge); + } + + int getFirstEdgeOffset(){ + return BigArrays.displacement(firstEdge); + } + + void setFirstEdge(long firstEdge) { + this.firstEdge = firstEdge; + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getId() + */ + @Override + public Long getId() { + return id; + } + + @Override + public void setId(Long id) { + this.id = id; + } + + long getLabelIndex(){ + return labelIndex; + } + + int getLabelIndexSegment(){ + return BigArrays.segment(labelIndex); + } + + int getLabelIndexOffset(){ + return BigArrays.displacement(labelIndex); + } + + void setLabelIndex(long labelIndex) { + this.labelIndex = labelIndex; + } + + int getCostsIndexSegment(){ + return BigArrays.segment(costsIndex); + } + + int getCostsIndexOffset(){ + return BigArrays.displacement(costsIndex); + } + + public long getCostsIndex() { + return costsIndex; + } + + void setCostsIndex(long costIndex) { + this.costsIndex = costIndex; + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#getLabel() + */ + @Override + public String getLabel() { + return label; + } + + @Override + public void setLabel(String label) { + this.label = label; + } + + @Override + public int[] getCosts() { + return costs; + } + + @Override + public void setCosts(int[] costs) { + this.costs = costs; + } + + /* (non-Javadoc) + * @see org.graphast.model.Node#toString() + */ + @Override + public String toString() { + return "FastGraphNode [id=" + id + ", externalId=" + externalId + ", latitude=" + latitude + + ", longitude=" + longitude + ", firstEdge=" + firstEdge + ", label="+ label + "]"; + } + + public boolean equals(Node n) { + if((n.getLatitude() == this.getLatitude() && (n.getLongitude() == this.getLongitude()) + && n.getCategory() == this.getCategory())) { + return true; + } + return false; + } + +} diff --git a/core/src/main/java/org/graphast/piecewise/BuilderDatasourceCSV.java b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceCSV.java new file mode 100644 index 0000000..2876a14 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceCSV.java @@ -0,0 +1,10 @@ +package org.graphast.piecewise; + + +public class BuilderDatasourceCSV implements IBuilderDatasource { + + @Override + public double[][] getData() { + return null; + } +} diff --git a/core/src/main/java/org/graphast/piecewise/BuilderDatasourceDB.java b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceDB.java new file mode 100644 index 0000000..2ca233a --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceDB.java @@ -0,0 +1,59 @@ +package org.graphast.piecewise; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.graphast.query.postgis.QueryPostgis; +import org.graphast.util.ConnectionJDBC; + +public class BuilderDatasourceDB implements IBuilderDatasource { + + private int FIELD_DATE_TIME = 1; + private int FIELD_DURACAO = 2; + + @Override + public double[][] getData() throws PiecewiseException { + + Connection connectionJDBC = null; + try { + connectionJDBC = ConnectionJDBC.getConnection(); + } catch (ClassNotFoundException | SQLException | IOException e) { + throw new PiecewiseException("[ERRO] Um erro ocorreu quando estava sendo aberta a conexão com DB."); + } + + ResultSet resultSet = null; + double[][] matrixResult; + try { + Statement statement = connectionJDBC.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); + resultSet = statement.executeQuery(QueryPostgis.QUERY_ALL_DATE_TIME_WITH_DURATE); + + resultSet.last(); + int size = resultSet.getRow(); + resultSet.beforeFirst(); + + matrixResult = new double[size][2]; + + int i = 0; + while (resultSet.next()) { + + Double dateTime = resultSet.getDouble(FIELD_DATE_TIME); + Double duracao = resultSet.getDouble(FIELD_DURACAO); + double[] result = new double[2]; + result[0] = duracao; + result[1] = dateTime; + + matrixResult[i] = result; + i++; + } + + } catch (SQLException e) { + throw new PiecewiseException("[ERRO] Um erro ocorreu ao pegar as informações no DB."); + } + + + return matrixResult; + } +} \ No newline at end of file diff --git a/core/src/main/java/org/graphast/piecewise/BuilderDatasourceStream.java b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceStream.java new file mode 100644 index 0000000..d51a3f7 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/BuilderDatasourceStream.java @@ -0,0 +1,10 @@ +package org.graphast.piecewise; + +public class BuilderDatasourceStream implements IBuilderDatasource { + + @Override + public double[][] getData() throws PiecewiseException { + return null; + } +} + diff --git a/core/src/main/java/org/graphast/piecewise/Function.java b/core/src/main/java/org/graphast/piecewise/Function.java new file mode 100644 index 0000000..04c6785 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/Function.java @@ -0,0 +1,35 @@ +package org.graphast.piecewise; + +public class Function { + + private long y; + + private long x; + + public Function(long y, long x) { + super(); + this.y = y; + this.x = x; + } + + public long getY() { + return y; + } + + public long getX() { + return x; + } + + public void setY(long y) { + this.y = y; + } + + public void setX(long x) { + this.x = x; + } + + + public long getValue(long timestamp) { + return 0; + } +} diff --git a/core/src/main/java/org/graphast/piecewise/GeneratorFunctionLoess.java b/core/src/main/java/org/graphast/piecewise/GeneratorFunctionLoess.java new file mode 100644 index 0000000..7c36022 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/GeneratorFunctionLoess.java @@ -0,0 +1,20 @@ +package org.graphast.piecewise; + + +public class GeneratorFunctionLoess implements IGeneratorFunction { + + private IManipulatorEngine engine; + + public GeneratorFunctionLoess() { + } + + public GeneratorFunctionLoess(IManipulatorEngine engine) { + this.engine = engine; + } + + @Override + public Function gerFuntionEdge(long idEdge, long timestamp) { + return engine.run(timestamp); + } +} + diff --git a/core/src/main/java/org/graphast/piecewise/GeneratorFunctionMatrix.java b/core/src/main/java/org/graphast/piecewise/GeneratorFunctionMatrix.java new file mode 100644 index 0000000..72e5e6d --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/GeneratorFunctionMatrix.java @@ -0,0 +1,17 @@ +package org.graphast.piecewise; + +public class GeneratorFunctionMatrix implements IGeneratorFunction { + + private IManipulatorEngine engine; + + public GeneratorFunctionMatrix(IManipulatorEngine engine) { + this.engine = engine; + } + + @Override + public Function gerFuntionEdge(long idEdge, long timestamp) { + engine.run(timestamp); + return null; + } +} + diff --git a/core/src/main/java/org/graphast/piecewise/IBuilderDatasource.java b/core/src/main/java/org/graphast/piecewise/IBuilderDatasource.java new file mode 100644 index 0000000..0cfbe64 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/IBuilderDatasource.java @@ -0,0 +1,7 @@ +package org.graphast.piecewise; + + +public interface IBuilderDatasource { + + public double[][] getData() throws PiecewiseException; +} diff --git a/core/src/main/java/org/graphast/piecewise/IGeneratorFunction.java b/core/src/main/java/org/graphast/piecewise/IGeneratorFunction.java new file mode 100644 index 0000000..117a377 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/IGeneratorFunction.java @@ -0,0 +1,6 @@ +package org.graphast.piecewise; + +public interface IGeneratorFunction { + + Function gerFuntionEdge(long idEdge, long timestamp); +} diff --git a/core/src/main/java/org/graphast/piecewise/IManipulatorEngine.java b/core/src/main/java/org/graphast/piecewise/IManipulatorEngine.java new file mode 100644 index 0000000..f8d88b6 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/IManipulatorEngine.java @@ -0,0 +1,6 @@ +package org.graphast.piecewise; + +public interface IManipulatorEngine { + + Function run(long x); +} diff --git a/core/src/main/java/org/graphast/piecewise/JsonTimeTravelToDB.java b/core/src/main/java/org/graphast/piecewise/JsonTimeTravelToDB.java new file mode 100644 index 0000000..b98d843 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/JsonTimeTravelToDB.java @@ -0,0 +1,64 @@ +package org.graphast.piecewise; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.graphast.query.postgis.QueryPostgis; +import org.graphast.util.ConnectionJDBC; +import org.json.JSONArray; +import org.json.JSONObject; + +public class JsonTimeTravelToDB { + + private final String FILE_JSON_TIME_TRAVEL = "time_travel.json"; + + private String FIELD_JSON_COORDINATES = "coordinates"; + private String FIELD_JSON_TIME = "entry_time"; + private String FIELD_JSON_TOTAL_TRAVEL = "total_time"; + + public void jsonToDB() throws PiecewiseException, SQLException, ClassNotFoundException, IOException { + + JSONObject jsonObject = new JSONObject(FILE_JSON_TIME_TRAVEL); + + JSONArray coordinates = jsonObject.getJSONArray(FIELD_JSON_COORDINATES); + double timeDay = jsonObject.getDouble(FIELD_JSON_TIME); + double totalTime = jsonObject.getDouble(FIELD_JSON_TOTAL_TRAVEL); + + Object latitude = coordinates.get(0); + Object longitude = coordinates.get(1); + + Connection connectionJDBC = null; + try { + connectionJDBC = ConnectionJDBC.getConnection(); + } catch (ClassNotFoundException | SQLException | IOException e) { + throw new PiecewiseException("[ERRO] Um erro ocorreu quando estava sendo aberta a conexão com DB."); + } + + PreparedStatement statement = connectionJDBC.prepareStatement(QueryPostgis.QUERY_CLOSER_LINESTRING); + statement.setString(0, latitude.toString()); + statement.setString(0, longitude.toString()); + + ResultSet resultSet = statement.executeQuery(QueryPostgis.QUERY_CLOSER_LINESTRING); + + while (resultSet.next()) { + + int idEdge = resultSet.getInt(0); + persisteValue(idEdge, timeDay, totalTime); + } + } + + private void persisteValue(int idEdge, double timeDay, double totalTime) throws SQLException, ClassNotFoundException, IOException { + + String insertTableSQL = QueryPostgis.INSERT_PIECEWISE; + + PreparedStatement preparedStatement = ConnectionJDBC.getConnection().prepareStatement(insertTableSQL); + preparedStatement.setInt(1, idEdge); + preparedStatement.setDouble(2, timeDay); + preparedStatement.setDouble(3, totalTime); + preparedStatement .executeUpdate(); + + } +} diff --git a/core/src/main/java/org/graphast/piecewise/ManipulatorJava.java b/core/src/main/java/org/graphast/piecewise/ManipulatorJava.java new file mode 100644 index 0000000..1987f43 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/ManipulatorJava.java @@ -0,0 +1,10 @@ +package org.graphast.piecewise; + +public class ManipulatorJava implements IManipulatorEngine { + + @Override + public Function run(long x) { + return null; + } +} + diff --git a/core/src/main/java/org/graphast/piecewise/ManipulatorR.java b/core/src/main/java/org/graphast/piecewise/ManipulatorR.java new file mode 100644 index 0000000..f947be3 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/ManipulatorR.java @@ -0,0 +1,110 @@ +package org.graphast.piecewise; + +import com.github.rcaller.rStuff.RCaller; +import com.github.rcaller.rStuff.RCode; + +public class ManipulatorR implements IManipulatorEngine { + + private static final String RSCRIPT = "/usr/bin/Rscript"; + private double[][] data; + + public ManipulatorR(double[][] coleta) { + this.data = coleta; + } + + @Override + public Function run(long x) { + + RCaller caller = new RCaller(); + RCode code = caller.getRCode(); + caller.setRscriptExecutable(RSCRIPT); + + code.addDoubleMatrix("matrix", data); + code.addRCode("dados.frame <- data.frame(matrix)"); + code.addRCode("dados.loess <- loess(dados.frame)"); + code.addRCode("xl <- with(dados.loess, seq(min(x), max(x), (max(x) - min(x))/1000))"); + code.addRCode("y.predict <- predict(dados.loess, xl)"); + code.addRCode("infl <- c(FALSE, diff(diff(y.predict)>0)!=0)"); + code.addRCode("pontoInicial <- cbind(xl, y.predict)[xl == min(xl),]"); + code.addRCode("pontosInflexao <- cbind(xl, y.predict)[infl,]"); + code.addRCode("pontoFinal <- cbind(xl, y.predict)[xl == max(xl),]"); + code.addRCode("allObjects <- list(pontoInicial=pontoInicial, pontoFinal=pontoFinal, pontosInflexao=pontosInflexao)"); + + caller.setRCode(code); + caller.runAndReturnResult("allObjects"); + + double[] pontoInicial = caller.getParser().getAsDoubleArray("pontoInicial"); + double[] pontosInflexao = caller.getParser().getAsDoubleArray("pontosInflexao"); + + PontoGeometrico pontoInicialGeo = new PontoGeometrico(pontoInicial[0], pontoInicial[1]); + PontoGeometrico pontoFinalGeo0 = new PontoGeometrico(pontosInflexao[0], pontosInflexao[pontosInflexao.length/2]); + + double coeficienteAngularAnterior = getCoeficienteAngular(pontoInicialGeo, pontoFinalGeo0); + double coeficienteLinearAnterior = getCoeficienteLinear(pontoInicialGeo, coeficienteAngularAnterior); + + + double yFinal = 0; + PontoGeometrico pontoGeo1 = null; + yFinal = coeficienteAngularAnterior; + + for (int i = 0; i < (pontosInflexao.length/2) - 1; i++) { + + pontoGeo1 = new PontoGeometrico(pontosInflexao[i], pontosInflexao[pontosInflexao.length/2+i]); + PontoGeometrico pontoGeo2 = new PontoGeometrico(pontosInflexao[i+1], pontosInflexao[pontosInflexao.length/2+(i+1)]); + double coeficienteAngularCurrent = getCoeficienteAngular(pontoGeo1, pontoGeo2); + double coeficienteLinearCurrent = getCoeficienteLinear(pontoGeo1, coeficienteAngularCurrent); + + yFinal = yFinal + (pontoGeo1.getX() * (coeficienteLinearAnterior - coeficienteLinearCurrent)); + + coeficienteAngularAnterior = coeficienteAngularCurrent; + coeficienteLinearAnterior = coeficienteLinearCurrent; + } + + double[] pontoFinal = caller.getParser().getAsDoubleArray("pontoFinal"); + + PontoGeometrico ponto1FinalGeo = new PontoGeometrico(pontosInflexao[(pontosInflexao.length/2)-1], + pontosInflexao[pontosInflexao.length - 1]); + PontoGeometrico ponto2FinalGeo = new PontoGeometrico(pontoFinal[0], pontoFinal[1]); + + double coeficienteAngularFinal = getCoeficienteAngular(ponto1FinalGeo, ponto2FinalGeo); + double coeficienteLinearFinal = getCoeficienteLinear(ponto1FinalGeo, coeficienteAngularFinal); + + yFinal = yFinal + (pontoGeo1.getX() * (coeficienteLinearAnterior - coeficienteLinearFinal)) + coeficienteAngularFinal * x; + + return null; + } + + private double getCoeficienteLinear(PontoGeometrico pontoInicialGeo, double coeficienteAngular) { + double gama = pontoInicialGeo.getY() - coeficienteAngular * pontoInicialGeo.getX(); + return gama; + } + + private double getCoeficienteAngular(PontoGeometrico pontoInicialGeo, PontoGeometrico pontoFinalGeo) { + double alfa = (pontoFinalGeo.getY() - pontoInicialGeo.getY()) / (pontoFinalGeo.getX() - pontoInicialGeo.getX()); + return alfa; + } + + class PontoGeometrico { + + double x; + double y; + + public PontoGeometrico(double x, double y) { + this.x = x; + this.y= y; + } + + public double getX() { + return x; + } + public void setX(double x) { + this.x = x; + } + public double getY() { + return y; + } + public void setY(double y) { + this.y = y; + } + } +} diff --git a/core/src/main/java/org/graphast/piecewise/PiecewiseException.java b/core/src/main/java/org/graphast/piecewise/PiecewiseException.java new file mode 100644 index 0000000..afcc460 --- /dev/null +++ b/core/src/main/java/org/graphast/piecewise/PiecewiseException.java @@ -0,0 +1,12 @@ +package org.graphast.piecewise; + +public class PiecewiseException extends Exception { + + private static final long serialVersionUID = 1L; + + public PiecewiseException(String string) { + super(string); + } + +} + diff --git a/core/src/main/java/org/graphast/query/dao/postgis/GraphastDAO.java b/core/src/main/java/org/graphast/query/dao/postgis/GraphastDAO.java new file mode 100644 index 0000000..ac18f9c --- /dev/null +++ b/core/src/main/java/org/graphast/query/dao/postgis/GraphastDAO.java @@ -0,0 +1,58 @@ +package org.graphast.query.dao.postgis; + +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.graphast.model.Node; +import org.graphast.model.NodeImpl; +import org.graphast.util.ConnectionJDBC; +import org.postgis.Point; + +public class GraphastDAO { + + private static final int FIELD_ID_TAXI = 1; + private final static int FIELD_POINT_TAXI = 2; + private final static int FIELD_ID_ROAD = 3; + + public ResultSet getPoints(String table) throws ClassNotFoundException, SQLException, IOException { + + String finalQuery = String.format(QueryPostgis.QUERY_POINT_ROAD.replace("TABLE_NAME", "%s"), table); + Statement statement = ConnectionJDBC.getConnection().createStatement(); + + return statement.executeQuery(finalQuery); + } + private void addNodeInMap( Map> map, int idRoad, Node node) { + if (!map.containsKey(idRoad)) { + map.put(idRoad, new ArrayList()); + } + map.get(idRoad).add(node); + } + public Map> getPoiTaxiFortaleza() throws ClassNotFoundException, SQLException, IOException { + + Map> mapIdRoads = new HashMap>(); + + String finalQuery = String.format(QueryPostgis.QUERY_POINT_TAXI); + Statement statement = ConnectionJDBC.getConnection().createStatement(); + ResultSet result = statement.executeQuery(finalQuery); + + while (result.next()) { + + String strPointTaxi = result.getString(FIELD_POINT_TAXI); + Point point = new Point(strPointTaxi); + int idTaxi = result.getInt(FIELD_ID_TAXI); + int idRoad = result.getInt(FIELD_ID_ROAD); + Node node = new NodeImpl(idTaxi, point.getY(), point.getX()); + node.setCategory(idTaxi); + node.setLabel(Integer.valueOf(idRoad).toString()); + addNodeInMap(mapIdRoads, idRoad, node); + } + + return mapIdRoads; + } +} diff --git a/core/src/main/java/org/graphast/query/dao/postgis/QueryPostgis.java b/core/src/main/java/org/graphast/query/dao/postgis/QueryPostgis.java new file mode 100644 index 0000000..259e052 --- /dev/null +++ b/core/src/main/java/org/graphast/query/dao/postgis/QueryPostgis.java @@ -0,0 +1,12 @@ +package org.graphast.query.dao.postgis; + +public interface QueryPostgis { + + String QUERY_ALL_DATE_TIME_WITH_DURATE = "SELECT date_time, duracao FROM tester;"; + + String QUERY_POINT_ROAD = "SELECT ro.gid, ST_AsText(st_makeline(st_linemerge(ro.geom))) " + + "FROM TABLE_NAME ro GROUP BY ro.gid ORDER BY ro.gid;"; + + String QUERY_POINT_TAXI = "SELECT t.id, ST_AsText(t.point_geo), t.gid FROM view_taxi_close_linestring t"; + +} diff --git a/core/src/main/java/org/graphast/query/knn/NearestNeighbor.java b/core/src/main/java/org/graphast/query/knn/NearestNeighbor.java index 642bc9a..21b10ba 100755 --- a/core/src/main/java/org/graphast/query/knn/NearestNeighbor.java +++ b/core/src/main/java/org/graphast/query/knn/NearestNeighbor.java @@ -1,63 +1,95 @@ -package org.graphast.query.knn; - -import java.util.ArrayList; - -public class NearestNeighbor implements Comparable { - private long id; - private int distance; - private ArrayList path; - - public NearestNeighbor() {} - - public NearestNeighbor(long id, int distance){ - this.id = id; - this.distance = distance; - this.path = new ArrayList(); - } - - public NearestNeighbor(long id, int distance, ArrayList path){ - this.id = id; - this.distance = distance; - this.path = path; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public int getDistance() { - return distance; - } - - public void setDistance(int distance) { - this.distance = distance; - } - - public ArrayList getPath() { - return path; - } - - public void setPath(ArrayList path) { - this.path = path; - } - - public String toString(){ - return "(NN:"+id+" TT: "+distance+ " Path: " + path + ")"; - } - - public int compareTo(NearestNeighbor o) { - int result; - if(distance == o.distance) result = 0; - else if(distance < o.distance) result = -1; - else result = 1; - return result; - } - - public boolean equals(NearestNeighbor o){ - return((id == o.id) && (distance == o.distance)); - } -} +package org.graphast.query.knn; + +import java.util.ArrayList; + +public class NearestNeighbor implements Comparable { + private long id; + private int distance; + private double travelTime; + private ArrayList path; + private int numberVisitedNodes; + + public NearestNeighbor() {} + + public NearestNeighbor(long id, int distance){ + this.id = id; + this.distance = distance; + this.path = new ArrayList(); + } + + public NearestNeighbor(long id, int distance, ArrayList path){ + this.id = id; + this.distance = distance; + this.path = path; + } + + public NearestNeighbor(long id, int distance, ArrayList path, int numberVisitedNodes){ + this(id, distance, path); + this.numberVisitedNodes = numberVisitedNodes; + } + + public NearestNeighbor(long id, double travelTime, ArrayList path, int numberVisitedNodes){ + this.id = id; + this.path = path; + this.travelTime = travelTime; + this.numberVisitedNodes = numberVisitedNodes; + } + + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public int getDistance() { + return distance; + } + + public void setDistance(int distance) { + this.distance = distance; + } + + public ArrayList getPath() { + return path; + } + + public void setPath(ArrayList path) { + this.path = path; + } + + public String toString(){ + return "(NN:"+id+" TT: "+distance+ " Path: " + path + + " Number Visited Nodes: " + numberVisitedNodes + ")"; + } + + public int compareTo(NearestNeighbor o) { + int result; + if(distance == o.distance) result = 0; + else if(distance < o.distance) result = -1; + else result = 1; + return result; + } + + public boolean equals(NearestNeighbor o){ + return((id == o.id) && (distance == o.distance)); + } + + public int getNumberVisitedNodes() { + return numberVisitedNodes; + } + + public void setNumberVisitedNodes(int numberVisitedNodes) { + this.numberVisitedNodes = numberVisitedNodes; + } + + public double getTravelTime() { + return travelTime; + } + + public void setTravelTime(double travelTime) { + this.travelTime = travelTime; + } +} diff --git a/core/src/main/java/org/graphast/query/knn/RouteQueueRNNEntry.java b/core/src/main/java/org/graphast/query/knn/RouteQueueRNNEntry.java new file mode 100644 index 0000000..4b839a0 --- /dev/null +++ b/core/src/main/java/org/graphast/query/knn/RouteQueueRNNEntry.java @@ -0,0 +1,25 @@ +package org.graphast.query.knn; + +import java.util.List; + +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.route.shortestpath.model.TimeEntry; + +/** + * Representa um taxista na malha com a rota do cliente a este. + * + */ +public class RouteQueueRNNEntry extends TimeEntry { + + private List routes; + + public RouteQueueRNNEntry(long id, int travelTime, int arrivalTime, long parentId, List routes) { + super(id, travelTime, arrivalTime, parentId); + this.routes = routes; + } + + public List getRoutes() { + return routes; + } + +} diff --git a/core/src/main/java/org/graphast/query/postgis/QueryPostgis.java b/core/src/main/java/org/graphast/query/postgis/QueryPostgis.java new file mode 100644 index 0000000..2ae067b --- /dev/null +++ b/core/src/main/java/org/graphast/query/postgis/QueryPostgis.java @@ -0,0 +1,9 @@ +package org.graphast.query.postgis; + +public interface QueryPostgis { + + String QUERY_ALL_DATE_TIME_WITH_DURATE = "SELECT date_time, duracao FROM tester;"; + String QUERY_CLOSER_LINESTRING = null; + String INSERT_PIECEWISE = "INSERT INTO public.piecewise(edgeId, timeDay, totalTime) VALUES (?, ?,?);"; + +} diff --git a/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsAnalysis.java b/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsAnalysis.java new file mode 100644 index 0000000..8149ce0 --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsAnalysis.java @@ -0,0 +1,141 @@ +package org.graphast.query.rnn; + +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.logging.Logger; + +import org.graphast.config.Configuration; +import org.graphast.exception.PathNotFoundException; +import org.graphast.importer.OSMDBImporter; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.util.BenchmarkMemory; +import org.graphast.util.DateUtils; +import org.graphast.util.NumberUtils; + +public class CompareRNNSearchsMethodsAnalysis { + private static final String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + protected static final Logger LOGGER = Logger.getGlobal(); + + public static void main(String[] args) throws IOException { + + runAnalysis("view_exp_1k", 10); + //runAnalysis("view_exp_10k", Integer.parseInt(args[0])); + //runAnalysis("view_exp_50k", Integer.parseInt(args[0])); + //runAnalysis("view_exp_100k", Integer.parseInt(args[0])); + } + + public static void runAnalysis(String tableName, int testTimes) throws IOException { + + OSMDBImporter importer = new OSMDBImporter(tableName, PATH_GRAPH+tableName); + GraphBounds graph = importer.execute(); + + OSMDBImporter importerReverse = new OSMDBImporter(tableName, PATH_GRAPH+tableName+"_reverse"); + GraphBounds graphReverse = importerReverse.execute(); + + + RNNBacktrackingSearch rnnDFS = new RNNBacktrackingSearch(graph); + RNNBreadthFirstSearch rnnBFS = new RNNBreadthFirstSearch(graphReverse); + + Date timeout = DateUtils.parseDate(00, 50, 00); + Date timestamp = DateUtils.parseDate(00, 00, 00); + + FileWriter rnnBacktrackingFileCsv = new FileWriter(tableName+"_rnn_baseline.csv"); + FileWriter rnnBFSFileCsv = new FileWriter(tableName+"_rnn_bfs_proposed_solution.csv"); + + for (int i = 0; i < testTimes; i++) { + Node customer = getRandomCustomerInGraph(graph); + runSearchAndWrite(graph, rnnDFS, customer, timeout, timestamp, rnnBacktrackingFileCsv); + runSearchAndWrite(graph, rnnBFS, customer, timeout, timestamp, rnnBFSFileCsv); + } + + rnnBacktrackingFileCsv.close(); + rnnBFSFileCsv.close(); + + } + + private static void runSearchAndWrite(GraphBounds graph, IRNNTimeDependent rnn, + Node customer, Date timeout, Date timestamp, FileWriter fileCsv) throws IOException { + try { + + long numberUseMemoryInit = BenchmarkMemory.getUsedMemory(); + long startTime = System.nanoTime(); + long ioProcessReadInit = 0; + long ioProcessWriteInit = 0; + + NearestNeighbor solution = null; + solution = rnn.search(customer, timeout, timestamp); + + long ioProcessReadEnd = 0; + long ioProcessWriteEnd = 0; + + long endTime = System.nanoTime(); + long numberUseMemoryFinal = BenchmarkMemory.getUsedMemory(); + + long time = endTime - startTime; + long numerUseMemory = (numberUseMemoryFinal - numberUseMemoryInit) / 1024; + + long read = ioProcessReadEnd - ioProcessReadInit; + long write = ioProcessWriteEnd - ioProcessWriteInit; + + System.out.println(" READ "+read); + System.out.println(" WRITE "+write); + + Long solutionId = null; + Double travelTime = null; + Integer nodesSize = null; + ArrayList path = null; + Long externalId = null; + int numberVisitedNodes = 0; + if(solution != null && solution.getPath()!=null) { + solutionId = solution.getId(); + travelTime = solution.getTravelTime(); + nodesSize = solution.getPath().size(); + path = solution.getPath(); + externalId = Integer.valueOf(graph.getNode(solution.getId()).getCategory()).longValue(); + numberVisitedNodes = solution.getNumberVisitedNodes(); + + String coordinatesCustomer = customer.getLongitude() + "," + customer.getLatitude(); + String gidCustomer = customer.getLabel(); + + Node nodePoi = graph.getNode(solutionId); + String poiCoordinate = nodePoi.getLongitude() + "," + nodePoi.getLatitude(); + String gidPoi = nodePoi.getLabel(); + + String coordinateNodeVisited = ""; + String gidVisited = ""; + for (Long visited : path) { + Node nodeVisited = graph.getNode(visited); + coordinateNodeVisited = coordinateNodeVisited + "(" + nodeVisited.getLongitude() + "," + nodeVisited.getLatitude() + ")"; + + gidVisited = gidVisited + "-" + nodeVisited.getLabel(); + } + + String currentLine = String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", coordinatesCustomer, + poiCoordinate, time, solutionId, externalId, travelTime, + nodesSize, path, coordinateNodeVisited, gidCustomer, gidPoi, gidVisited, numberVisitedNodes, numerUseMemory) + "\n"; + + + System.out.println(currentLine); + fileCsv.write(currentLine); + } + } catch(PathNotFoundException e) { + System.err.println(String.format("Customer %s (%s, %s) has no POI in subgraph", customer.getId(), customer.getLatitude(), customer.getLongitude())); + } + } + + private static Node getRandomCustomerInGraph(GraphBounds graph) { + Node node; + double[] bounds = new double[]{-3.710467, -38.591078, -3.802376, -38.465530}; + do { + long id = Double.valueOf(NumberUtils.generatePdseurandom(0, Long.valueOf(graph.getNumberOfNodes()-1).intValue())).longValue(); + node = graph.getNode(id); + } while(node.getCategory()!=-1 || node.getLatitude()>bounds[0] || node.getLatitude()bounds[3]); + return node; + } + +} diff --git a/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsSyntheticAnalysis.java b/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsSyntheticAnalysis.java new file mode 100644 index 0000000..c1eeb68 --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/CompareRNNSearchsMethodsSyntheticAnalysis.java @@ -0,0 +1,131 @@ +package org.graphast.query.rnn; + +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.logging.Logger; + +import org.graphast.config.Configuration; +import org.graphast.exception.PathNotFoundException; +import org.graphast.importer.GraphGeneratorGrid; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.util.DateUtils; +import org.graphast.util.NumberUtils; + +public class CompareRNNSearchsMethodsSyntheticAnalysis { + + private static final String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + protected static final Logger LOGGER = Logger.getGlobal(); + + public static void main(String[] args) throws IOException { + + int side = 0; + switch (args[0]) { + case "1k": + side = 32; + break; + case "10k": + side = 100; + break; + case "100k": + side = 316; + break; + case "1000k": + side = 1000; + break; + default: + break; + } + + runAnalysis(args[0], side, Integer.parseInt(args[1]), Integer.parseInt(args[2])); + } + + public static void runAnalysis(String experimentName, int side, int percentagemPoi, int testTimes) throws IOException { + + GraphGeneratorGrid graphSynthetic = new GraphGeneratorGrid(PATH_GRAPH+experimentName, side, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + GraphGeneratorGrid graphSyntheticReverse = new GraphGeneratorGrid(PATH_GRAPH+experimentName, side, percentagemPoi); + graphSyntheticReverse.generateGraph(); + GraphBounds graphReverse = graphSynthetic.getGraph(); + + + RNNBacktrackingSearch rnnDFS = new RNNBacktrackingSearch(graph); + RNNBreadthFirstSearch rnnBFS = new RNNBreadthFirstSearch(graphReverse); + + Date timeout = DateUtils.parseDate(00, 50, 00); + Date timestamp = DateUtils.parseDate(00, 00, 00); + + FileWriter rnnDFSFileCsv = new FileWriter(experimentName+"_"+percentagemPoi+"_rnn_dfs_baseline.csv"); + FileWriter rnnBFSFileCsv = new FileWriter(experimentName+"_"+percentagemPoi+"_rnn_bfs_solution.csv"); + + for (int i = 0; i < testTimes; i++) { + Node customer = getRandomCustomerInGraph(graph); + runSearchAndWrite(graph, rnnDFS, customer, timeout, timestamp, rnnDFSFileCsv); + runSearchAndWrite(graph, rnnBFS, customer, timeout, timestamp, rnnBFSFileCsv); + } + + rnnBFSFileCsv.close(); + rnnDFSFileCsv.close(); + } + + private static void runSearchAndWrite(GraphBounds graph, IRNNTimeDependent rnn, + Node customer, Date timeout, Date timestamp, FileWriter fileCsv) throws IOException { + try { + long startTime = System.nanoTime(); + NearestNeighbor solution = rnn.search(customer, timeout, timestamp); + long endTime = System.nanoTime(); + + long time = endTime - startTime; + + Long solutionId = null; + Double travelTime = null; + Integer nodesSize = null; + ArrayList path = null; + int numberVisitedNodes = 0; + if(solution != null && solution.getPath()!=null) { + solutionId = solution.getId(); + travelTime = solution.getTravelTime(); + nodesSize = solution.getPath().size(); + path = solution.getPath(); + numberVisitedNodes = solution.getNumberVisitedNodes(); + + String coordinatesCustomer = customer.getLongitude() + "," + customer.getLatitude(); + + Node nodePoi = graph.getNode(solutionId); + String poiCoordinate = nodePoi.getLongitude() + "," + nodePoi.getLatitude(); + String gidPoi = nodePoi.getLabel(); + + String coordinateNodeVisited = ""; + for (Long visited : path) { + Node nodeVisited = graph.getNode(visited); + coordinateNodeVisited = coordinateNodeVisited + "(" + nodeVisited.getLongitude() + "," + nodeVisited.getLatitude() + ")"; + } + + String currentLine = String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", coordinatesCustomer, + poiCoordinate, time, solutionId, travelTime, nodesSize, path, coordinateNodeVisited, gidPoi, numberVisitedNodes) + "\n"; + + + System.out.println(currentLine); + + fileCsv.write(currentLine); + } + } catch(PathNotFoundException e) { + System.err.println(String.format("Customer %s (%s, %s) has no POI in subgraph", customer.getId(), customer.getLatitude(), customer.getLongitude())); + } + } + + + private static Node getRandomCustomerInGraph(GraphBounds graph) { + Node node; + do { + long id = Double.valueOf(NumberUtils.generatePdseurandom(0, Long.valueOf(graph.getNumberOfNodes()-1).intValue())).longValue(); + node = graph.getNode(id); + } while(node.getCategory()!=-1); + return node; + } +} diff --git a/core/src/main/java/org/graphast/query/rnn/IRNNTimeDependent.java b/core/src/main/java/org/graphast/query/rnn/IRNNTimeDependent.java new file mode 100644 index 0000000..bcbe2b6 --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/IRNNTimeDependent.java @@ -0,0 +1,13 @@ +package org.graphast.query.rnn; + +import java.util.Date; + +import org.graphast.exception.PathNotFoundException; +import org.graphast.model.Node; +import org.graphast.query.knn.NearestNeighbor; + +public interface IRNNTimeDependent { + + public NearestNeighbor search(Node root, Date timeout, Date timestamp) throws PathNotFoundException; + +} diff --git a/core/src/main/java/org/graphast/query/rnn/RNNBacktrackingSearch.java b/core/src/main/java/org/graphast/query/rnn/RNNBacktrackingSearch.java new file mode 100644 index 0000000..d9a83a2 --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/RNNBacktrackingSearch.java @@ -0,0 +1,87 @@ +package org.graphast.query.rnn; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.graphast.exception.PathNotFoundException; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.route.shortestpath.dijkstra.Dijkstra; +import org.graphast.query.route.shortestpath.dijkstra.DijkstraLinearFunction; +import org.graphast.query.route.shortestpath.model.Path; +import org.graphast.util.DateUtils; + +public class RNNBacktrackingSearch implements IRNNTimeDependent { + + private GraphBounds graph; + + public RNNBacktrackingSearch(GraphBounds graphBounds) { + this.graph = graphBounds; + } + + public NearestNeighbor search(Node root, Date timeout, Date timestamp) + throws PathNotFoundException { + + long maxTravelTimeMillisenconds = DateUtils.dateToMilli(timeout); + double bestTravelTime = maxTravelTimeMillisenconds; + long currentPoi = -1; + Path pathResult = null; + int numberVisitedNodes = 0; + + Dijkstra dijkstraShortestPathLinearFunction = new DijkstraLinearFunction(graph); + + for (Long poi : graph.getPoiIds()) { + try { + Node target = graph.getNode(poi); + Path path = dijkstraShortestPathLinearFunction.shortestPath( + target.getId(), root.getId(), timestamp); + + if (path.getTotalCost() <= maxTravelTimeMillisenconds + && path.getTotalCost() <= bestTravelTime) { + currentPoi = target.getId(); + bestTravelTime = path.getTotalCost(); + pathResult = path; + numberVisitedNodes = numberVisitedNodes + path.getNumberVisitedNodes(); + } + } catch (PathNotFoundException e) { + // System.err.println(e.getMessage()); + } + } + + if (currentPoi > -1) { + NearestNeighbor nearestNeighbor = createNN(root, currentPoi, numberVisitedNodes, pathResult); + return nearestNeighbor; + } + + throw new PathNotFoundException( + "target not found for root and set timestamp"); + } + + private NearestNeighbor createNN(Node root, long currentPoi, int numberVisitedNodes, Path path) { + + NearestNeighbor nearestNeighbor = new NearestNeighbor(); + + double totalCostInMilissegundo = path.getTotalCost(); + double totalCostInNanosegundos = totalCostInMilissegundo * Math.pow(10, 6); + + nearestNeighbor.setTravelTime(totalCostInNanosegundos); + nearestNeighbor.setId(currentPoi); + nearestNeighbor.setNumberVisitedNodes(numberVisitedNodes); + + ArrayList arrayPath = new ArrayList(); + List edges = path.getEdges(); + + if (edges != null) { + for (Long edge : edges) { + arrayPath.add(graph.getEdge(edge).getFromNode()); + } + } + + arrayPath.add(root.getId()); + nearestNeighbor.setPath(arrayPath); + + return nearestNeighbor; + } +} \ No newline at end of file diff --git a/core/src/main/java/org/graphast/query/rnn/RNNBreadthFirstSearch.java b/core/src/main/java/org/graphast/query/rnn/RNNBreadthFirstSearch.java new file mode 100644 index 0000000..148b96f --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/RNNBreadthFirstSearch.java @@ -0,0 +1,144 @@ +package org.graphast.query.rnn; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Set; + +import org.graphast.exception.PathNotFoundException; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.util.DateUtils; + +public class RNNBreadthFirstSearch implements IRNNTimeDependent{ + + private GraphBounds graph; + + public RNNBreadthFirstSearch(GraphBounds graph) { + this.graph = graph; + this.graph.reverseGraph(); + } + + public NearestNeighbor search(Node customer, Date maxTravelTime, Date startServiceTime) { + + int numberVisitedNodes = 0; + + if (graph.getPoi(customer.getId()) != null) { + ArrayList path = new ArrayList(); + path.add(customer.getId()); + numberVisitedNodes = numberVisitedNodes + 1; + + NearestNeighbor nearestNeighbor = new NearestNeighbor(customer.getId(), 0, path); + nearestNeighbor.setNumberVisitedNodes(numberVisitedNodes); + return nearestNeighbor; + } + + PriorityQueue queue = new PriorityQueue(); + Map> parents = new HashMap>(); + + long maxTravelTimeMilliseconds = DateUtils.dateToMilli(maxTravelTime); + long hourServiceTimeMilliseconds = DateUtils.dateToMilli(startServiceTime); + long startServiceTimeMilliseconds = hourServiceTimeMilliseconds + maxTravelTimeMilliseconds; + + init(customer, queue, parents, hourServiceTimeMilliseconds, startServiceTimeMilliseconds); + RouteQueueRNNEntry current = null; + Set visited = new HashSet<>(); + + while(!queue.isEmpty()) { + + current = queue.poll(); + numberVisitedNodes = numberVisitedNodes + 1; + if (visited.contains(current.getId())) { + continue; + } else { + visited.add(current.getId()); + } + + if(current.getTravelTime() > maxTravelTimeMilliseconds) { + throw new PathNotFoundException(String.format("not found path in reverse graph for parameter time %s milliseconds.", + maxTravelTimeMilliseconds)); + } + + if (graph.getPoi(current.getId()) != null) { + + double totalCostInMilissegundo = current.getTravelTime(); + double totalCostInNanosegundos = totalCostInMilissegundo * Math.pow(10, 6); + ArrayList pathToTaxi = pathToTaxi(current.getId(), customer.getId(), parents); + + NearestNeighbor nearestNeighbor = new NearestNeighbor(current.getId(),totalCostInNanosegundos, + pathToTaxi, numberVisitedNodes); + return nearestNeighbor; + } + + // Acessa os vizinhos do primeiro vértice da pilha, no caso os vizinho do vértice que representa o cliente. + HashMap neighbors = graph.accessNeighborhood(graph.getNode(current.getId()), current.getArrivalTime()); + + for (Node neighbor : neighbors.keySet()) { + numberVisitedNodes = numberVisitedNodes + 1; + if (visited.contains(neighbor.getId())) { + continue; + } + int travelTime = current.getTravelTime() + neighbors.get(neighbor); + if (travelTime > maxTravelTimeMilliseconds) { + continue; + } + + List parents_list = new ArrayList(); + parents_list.add(current.getId()); + parents.put(neighbor.getId(), parents_list); + + int arrivalTime = current.getArrivalTime() - neighbors.get(neighbor); + + RouteQueueRNNEntry newRouteQueueTaxiEntry = new RouteQueueRNNEntry(neighbor.getId(), travelTime, + arrivalTime, current.getId(), current.getRoutes()); + queue.offer(newRouteQueueTaxiEntry); + } + + } + + throw new PathNotFoundException("not found path in reverse graph"); + } + + private ArrayList pathToTaxi(Long idTaxista, Long idCustomer, Map> parents) { + + ArrayList idsPath = new ArrayList(); + idsPath.add(idTaxista); + + Long idAnterior = idTaxista; + Set keySet = parents.keySet(); + for (Iterator iter = keySet.iterator(); iter.hasNext(); ) { + Long next = iter.next(); + if(next.equals(idAnterior) && !next.equals(idCustomer)) { + List list = parents.get(next); + for (Long long1 : list) { + idsPath.add(long1); + idAnterior = long1; + iter = keySet.iterator(); + } + } + } + if(!idsPath.contains(idCustomer)) { + idsPath.add(idCustomer); + } + + return idsPath; + } + + private void init(Node customer, PriorityQueue queue, Map> parents, long startServiceTime, long arrivedTime) { + + int travelTime = Long.valueOf(startServiceTime).intValue(); + int arrivalTime = Long.valueOf(arrivedTime).intValue(); + + List parents_list = new ArrayList(); + parents_list.add(Long.valueOf(-1)); + parents.put(customer.getId(), parents_list); + + queue.offer(new RouteQueueRNNEntry(customer.getId(), travelTime, arrivalTime, -1, new ArrayList())); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/graphast/query/rnn/RouteQueueRNNEntry.java b/core/src/main/java/org/graphast/query/rnn/RouteQueueRNNEntry.java new file mode 100644 index 0000000..515ee3b --- /dev/null +++ b/core/src/main/java/org/graphast/query/rnn/RouteQueueRNNEntry.java @@ -0,0 +1,25 @@ +package org.graphast.query.rnn; + +import java.util.List; + +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.route.shortestpath.model.TimeEntry; + +/** + * Representa um taxista na malha com a rota do cliente a este. + * + */ +public class RouteQueueRNNEntry extends TimeEntry { + + private List routes; + + public RouteQueueRNNEntry(long id, int travelTime, int arrivalTime, long parentId, List routes) { + super(id, travelTime, arrivalTime, parentId); + this.routes = routes; + } + + public List getRoutes() { + return routes; + } + +} diff --git a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/Dijkstra.java b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/Dijkstra.java index 29558f0..9a2b0c9 100644 --- a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/Dijkstra.java +++ b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/Dijkstra.java @@ -1,105 +1,112 @@ -package org.graphast.query.route.shortestpath.dijkstra; - -import static org.graphast.util.NumberUtils.convertToInt; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.PriorityQueue; - -import org.graphast.exception.PathNotFoundException; -import org.graphast.model.Graph; -import org.graphast.model.GraphBounds; -import org.graphast.model.Node; -import org.graphast.query.route.shortestpath.AbstractShortestPathService; -import org.graphast.query.route.shortestpath.model.Path; -import org.graphast.query.route.shortestpath.model.RouteEntry; -import org.graphast.query.route.shortestpath.model.TimeEntry; -import org.graphast.util.DateUtils; - -public abstract class Dijkstra extends AbstractShortestPathService { - - //private Logger logger = LoggerFactory.getLogger(this.getClass()); - - public Dijkstra(GraphBounds graphBounds) { - super(graphBounds); - } - - public Dijkstra(Graph graph) { - super(graph); - } - - //TODO Double check this method!! - //TODO Create tests!! - protected List reconstructPath(long id, HashMap parents){ - RouteEntry re = parents.get(id); - long parent = re.getId(); - List path = new ArrayList(); - path.add(re); - while(parent != -1){ - re = parents.get(parent); - if (re != null) { - path.add(re); - parent = re.getId(); - } else { - break; - } - } - Collections.reverse(path); - return path; - } - - public Path shortestPath(Node source, Node target, Date time) { - PriorityQueue queue = new PriorityQueue(); - HashMap wasTraversed = new HashMap(); - HashMap parents = new HashMap(); - TimeEntry removed = null; - int targetId = convertToInt(target.getId()); - int t = DateUtils.dateToMilli(time); - - init(source, target, queue, parents, t); - - while(!queue.isEmpty()){ - removed = queue.poll(); - wasTraversed.put(removed.getId(), wasRemoved); - - if(removed.getId() == targetId) { - Path path = new Path(); - path.constructPath(removed.getId(), parents, graph); - return path; - } - - expandVertex(target, removed, wasTraversed, queue, parents); - } - throw new PathNotFoundException("Path not found between (" + source.getLatitude() + "," + source.getLongitude() + ") and (" - + target.getLatitude() + "," + target.getLongitude() + ")"); - } - - public void init(Node source, Node target, PriorityQueue queue, - HashMap parents, int t){ - int sid = convertToInt(source.getId()); - - queue.offer(new TimeEntry(sid, 0, t, -1)); - } - - public abstract void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, - PriorityQueue queue, HashMap parents); - - @Override - public Path shortestPath(Node source, Node target) { - return shortestPath(source, target, null); - } - - @Override - public Path shortestPath(long source, long target) { - return shortestPath(source, target, null); - } - - @Override - public Path shortestPath(long source, long target, Date time) { - return shortestPath(graph.getNode(source), graph.getNode(target), time); - } - -} +package org.graphast.query.route.shortestpath.dijkstra; + +import static org.graphast.util.NumberUtils.convertToInt; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Set; + +import org.graphast.exception.PathNotFoundException; +import org.graphast.model.Graph; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.route.shortestpath.AbstractShortestPathService; +import org.graphast.query.route.shortestpath.model.Path; +import org.graphast.query.route.shortestpath.model.RouteEntry; +import org.graphast.query.route.shortestpath.model.TimeEntry; +import org.graphast.util.DateUtils; + +public abstract class Dijkstra extends AbstractShortestPathService { + + //private Logger logger = LoggerFactory.getLogger(this.getClass()); + + public Dijkstra(GraphBounds graphBounds) { + super(graphBounds); + } + + public Dijkstra(Graph graph) { + super(graph); + } + + //TODO Double check this method!! + //TODO Create tests!! + protected List reconstructPath(long id, HashMap parents){ + RouteEntry re = parents.get(id); + long parent = re.getId(); + List path = new ArrayList(); + path.add(re); + while(parent != -1){ + re = parents.get(parent); + if (re != null) { + path.add(re); + parent = re.getId(); + } else { + break; + } + } + Collections.reverse(path); + return path; + } + + public Path shortestPath(Node source, Node target, Date time) { + PriorityQueue queue = new PriorityQueue(); + HashMap wasTraversed = new HashMap(); + Set allWasViseted = new HashSet(); + HashMap parents = new HashMap(); + TimeEntry removed = null; + int targetId = convertToInt(target.getId()); + int timeInMilli = DateUtils.dateToMilli(time); + + init(source, target, queue, parents, timeInMilli); + allWasViseted.add(source.getId()); + + while(!queue.isEmpty()) { + removed = queue.poll(); + long idRemoved = removed.getId(); + wasTraversed.put(idRemoved, wasRemoved); + + if(removed.getId() == targetId) { + Path path = new Path(); + path.constructPath(removed.getId(), parents, graph); + path.setNumberVisitedNodes(allWasViseted.size()); + return path; + } + + expandVertex(target, removed, wasTraversed, allWasViseted, queue, parents); + } + + throw new PathNotFoundException("Path not found between (" + source.getLatitude() + "," + source.getLongitude() + ") and (" + + target.getLatitude() + "," + target.getLongitude() + ")"); + } + + public void init(Node source, Node target, PriorityQueue queue, + HashMap parents, int t){ + int sid = convertToInt(source.getId()); + + queue.offer(new TimeEntry(sid, 0, t, -1)); + } + + public abstract void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, + Set wasVisited, PriorityQueue queue, HashMap parents); + + @Override + public Path shortestPath(Node source, Node target) { + return shortestPath(source, target, null); + } + + @Override + public Path shortestPath(long source, long target) { + return shortestPath(source, target, null); + } + + @Override + public Path shortestPath(long source, long target, Date time) { + return shortestPath(graph.getNode(source), graph.getNode(target), time); + } + +} diff --git a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraConstantWeight.java b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraConstantWeight.java index c33fc6d..aaba4d7 100644 --- a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraConstantWeight.java +++ b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraConstantWeight.java @@ -1,79 +1,80 @@ -package org.graphast.query.route.shortestpath.dijkstra; - -import it.unimi.dsi.fastutil.longs.Long2IntMap; - -import java.util.HashMap; -import java.util.PriorityQueue; - -import org.graphast.model.Edge; -import org.graphast.model.Graph; -import org.graphast.model.GraphBounds; -import org.graphast.model.Node; -import org.graphast.query.route.shortestpath.model.RouteEntry; -import org.graphast.query.route.shortestpath.model.TimeEntry; - -public class DijkstraConstantWeight extends Dijkstra { - - public DijkstraConstantWeight(Graph graph) { - super(graph); - } - - public DijkstraConstantWeight(GraphBounds graphBounds) { - super(graphBounds); - } - - public void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, - PriorityQueue queue, HashMap parents){ - - Long2IntMap neig = graph.accessNeighborhood(graph.getNode(removed.getId())); - - for (long vid : neig.keySet()) { - - int arrivalTime = graph.getArrival(removed.getArrivalTime(), neig.get(vid)); - int travelTime = removed.getTravelTime() + neig.get(vid); - TimeEntry newEntry = new TimeEntry( vid, travelTime, arrivalTime, removed.getId()); - - Edge edge = null; - int distance = -1; - - if (!wasTraversed.containsKey(vid)) { - - queue.offer(newEntry); - wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); - - distance = neig.get(vid); - edge = getEdge(removed.getId(), vid, distance); - parents.put(vid, new RouteEntry(removed.getId(), distance/17, edge.getId(), edge.getLabel())); - } else { - - int cost = wasTraversed.get(vid); - - if (cost != wasRemoved) { - if(cost > newEntry.getTravelTime()) { - queue.remove(newEntry); - queue.offer(newEntry); - wasTraversed.remove(newEntry.getId()); - wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); - - parents.remove(vid); - distance = neig.get(vid); - edge = getEdge(removed.getId(), vid, distance); - parents.put(vid, new RouteEntry(removed.getId(), distance/17, edge.getId(), edge.getLabel())); - } - } - } - } - } - - private Edge getEdge(long fromNodeId, long toNodeId, int distance) { - Edge edge = null; - for(Long outEdge : graph.getOutEdges(fromNodeId)) { - edge = graph.getEdge(outEdge); - if ((int) edge.getToNode() == toNodeId && edge.getDistance() == distance) { - break; - } - } - return edge; - } - -} +package org.graphast.query.route.shortestpath.dijkstra; + +import it.unimi.dsi.fastutil.longs.Long2IntMap; + +import java.util.HashMap; +import java.util.PriorityQueue; +import java.util.Set; + +import org.graphast.model.Edge; +import org.graphast.model.Graph; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.route.shortestpath.model.RouteEntry; +import org.graphast.query.route.shortestpath.model.TimeEntry; + +public class DijkstraConstantWeight extends Dijkstra { + + public DijkstraConstantWeight(Graph graph) { + super(graph); + } + + public DijkstraConstantWeight(GraphBounds graphBounds) { + super(graphBounds); + } + + public void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, Set wasVisited, + PriorityQueue queue, HashMap parents){ + + Long2IntMap neig = graph.accessNeighborhood(graph.getNode(removed.getId())); + + for (long vid : neig.keySet()) { + + int arrivalTime = graph.getArrival(removed.getArrivalTime(), neig.get(vid)); + int travelTime = removed.getTravelTime() + neig.get(vid); + TimeEntry newEntry = new TimeEntry( vid, travelTime, arrivalTime, removed.getId()); + + Edge edge = null; + int distance = -1; + + if (!wasTraversed.containsKey(vid)) { + + queue.offer(newEntry); + wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); + + distance = neig.get(vid); + edge = getEdge(removed.getId(), vid, distance); + parents.put(vid, new RouteEntry(removed.getId(), distance/17, edge.getId(), edge.getLabel())); + } else { + + int cost = wasTraversed.get(vid); + + if (cost != wasRemoved) { + if(cost > newEntry.getTravelTime()) { + queue.remove(newEntry); + queue.offer(newEntry); + wasTraversed.remove(newEntry.getId()); + wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); + + parents.remove(vid); + distance = neig.get(vid); + edge = getEdge(removed.getId(), vid, distance); + parents.put(vid, new RouteEntry(removed.getId(), distance/17, edge.getId(), edge.getLabel())); + } + } + } + } + } + + private Edge getEdge(long fromNodeId, long toNodeId, int distance) { + Edge edge = null; + for(Long outEdge : graph.getOutEdges(fromNodeId)) { + edge = graph.getEdge(outEdge); + if ((int) edge.getToNode() == toNodeId && edge.getDistance() == distance) { + break; + } + } + return edge; + } + +} diff --git a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraLinearFunction.java b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraLinearFunction.java index f419a06..f544221 100755 --- a/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraLinearFunction.java +++ b/core/src/main/java/org/graphast/query/route/shortestpath/dijkstra/DijkstraLinearFunction.java @@ -1,228 +1,230 @@ -package org.graphast.query.route.shortestpath.dijkstra; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.PriorityQueue; -import java.util.Set; - -import org.graphast.model.Edge; -import org.graphast.model.Graph; -import org.graphast.model.GraphBounds; -import org.graphast.model.Node; -import org.graphast.query.model.Bound; -import org.graphast.query.model.QueueEntry; -import org.graphast.query.route.shortestpath.model.RouteEntry; -import org.graphast.query.route.shortestpath.model.TimeEntry; - -import it.unimi.dsi.fastutil.longs.Long2DoubleMap; -import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.longs.LongSet; - -public class DijkstraLinearFunction extends Dijkstra{ - - public DijkstraLinearFunction(Graph graph) { - super(graph); - } - - public DijkstraLinearFunction(GraphBounds graphBounds) { - super(graphBounds); - } - - public void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, - PriorityQueue queue, HashMap parents){ - - HashMap neig = graph.accessNeighborhood(graph.getNode(removed.getId()), removed.getArrivalTime()); - - for (Node v : neig.keySet()) { - long vid = v.getId(); - int at = graph.getArrival(removed.getArrivalTime(), neig.get(v)); - int tt = removed.getTravelTime() + neig.get(v); - TimeEntry newEntry = new TimeEntry( vid, tt, at, removed.getId()); - - Edge edge = null; - int distance = -1; - - if(!wasTraversed.containsKey(vid)){ - queue.offer(newEntry); - wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); - - distance = neig.get(v); - edge = getEdge(removed.getId(), vid, distance); - parents.put(vid, new RouteEntry(removed.getId(), distance, edge.getId(), edge.getLabel())); - }else{ - int cost = wasTraversed.get(vid); - if(cost != wasRemoved){ - if(cost>newEntry.getTravelTime()){ - queue.remove(newEntry); - queue.offer(newEntry); - wasTraversed.remove(newEntry.getId()); - wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); - - parents.remove(v); - distance = neig.get(v); - edge = getEdge(removed.getId(), vid, distance); - parents.put(vid, new RouteEntry(removed.getId(), distance, edge.getId(), edge.getLabel())); - } - } - } - } - } - - private Edge getEdge(long fromNodeId, long toNodeId, int distance) { - Edge edge = null; - for(Long outEdge : graph.getOutEdges(fromNodeId)) { - edge = graph.getEdge(outEdge); - if ((int) edge.getToNode() == toNodeId && edge.getDistance() == distance) { - break; - } - } - return edge; - } - - public List shortestPathCategories(long nodeId, Set categoriesIds, short graphType){ - - //TODO Change this PriorityQueue to some FastUtil structure - PriorityQueue unsettledNodes = new PriorityQueue(); - - LongSet settledNodes = new LongOpenHashSet(); - Long2IntMap shortestDistances = new Long2IntOpenHashMap(); - - Map bounds = new HashMap(); - int upper = Integer.MIN_VALUE; - int waitingTime, timeToService; - - shortestDistances.put(nodeId, 0); - - /* - * This queryEntry represents the travel time from this nodeId to - * another vertex (this vertex can be, for example, a PoI. In this - * way, the queryEntry is going to represent the travel time from - * the nodeId to a PoI.). - */ - QueueEntry queryEntry = new QueueEntry(nodeId, 0); - unsettledNodes.add(queryEntry); - - while ((queryEntry = unsettledNodes.poll()) != null){ - - if(bounds.keySet().containsAll(categoriesIds) && queryEntry.getTravelTime() > upper){ - // Use ArrayList because bounds.values() is not Serializable - return new ArrayList(bounds.values()); - } - - if(!settledNodes.contains(queryEntry.getId())) { - - settledNodes.add(queryEntry.getId()); - - Node poi = graphBounds.getPoi(queryEntry.getId()); - - if(poi != null) { - - int cat = poi.getCategory(); - - waitingTime = graphBounds.poiGetCost(queryEntry.getId(), graphType); - timeToService = queryEntry.getTravelTime() + waitingTime; - - if(bounds.keySet().contains(cat)) { - - int cost = bounds.get(cat).getCost(); - - if(timeToService < cost) bounds.put(cat, new Bound(queryEntry.getId(), timeToService)); -// if(timeToService < cost) bounds.put(e.getId(), new Bound(e.getId(), timeToService)); - upper = updateUpper(bounds); - - } else { - - bounds.put(cat, new Bound(queryEntry.getId(), timeToService)); - if(timeToService > upper) upper = timeToService; - - } - } - - expandVertex(queryEntry, settledNodes, shortestDistances, unsettledNodes, graphType); - - } - } - - // Use ArrayList because bounds.values() is not Serializable - return new ArrayList(bounds.values()); - } - - public int updateUpper(Map bounds){ - int upper = Integer.MIN_VALUE; - for(Bound b: bounds.values()){ - if(b.getCost() > upper) upper = b.getCost(); - } - return upper; - } - - public void expandVertex(QueueEntry e, LongSet settledNodes, Long2IntMap shortestDistances, - PriorityQueue unsettledNodes){ - - expandVertex(e, settledNodes, shortestDistances, unsettledNodes, (short) 0); - - } - - public void expandVertex(QueueEntry e, LongSet settledNodes, Long2IntMap shortestDistances, - PriorityQueue unsettledNodes, short graphType){ - - Long2IntMap adjacents = graphBounds.accessNeighborhood(graphBounds.getNode(e.getId()), graphType, 0); - - if(adjacents != null) { - - for (long v : adjacents.keySet()) { - - long nodeId = v; - - if (settledNodes.contains(nodeId)) continue; - - int shortDist = getShortestDistance(e.getId(), shortestDistances) + adjacents.get(v); - - if (shortDist < getShortestDistance(nodeId, shortestDistances)) - { - // assign new shortest distance and mark unsettled - - QueueEntry eNew = new QueueEntry(nodeId, shortDist); - unsettledNodes.remove(eNew); - unsettledNodes.add(eNew); - shortestDistances.put(nodeId, shortDist); - } - } - } - } - - public int getShortestDistance(long id, Long2IntMap minCost) - { - if(minCost.containsKey(id)) - return minCost.get(id); - else - return Integer.MAX_VALUE; - } - - public Long2DoubleMap shortestPath(long v){ - PriorityQueue unsettledNodes = new PriorityQueue(); - LongSet settledNodes = new LongOpenHashSet(); - Long2IntMap shortestDistances = new Long2IntOpenHashMap(); - Long2DoubleMap distance = new Long2DoubleOpenHashMap(); - - shortestDistances.put(v, 0); - distance.put(v, 0); - QueueEntry e = new QueueEntry(v, 0); - unsettledNodes.add(e); - - while ((e = unsettledNodes.poll()) != null){ - if(!settledNodes.contains(e.getId())){ - settledNodes.add(e.getId()); - distance.put(e.getId(), e.getTravelTime()); - - expandVertex(e, settledNodes, shortestDistances, unsettledNodes, (short)0); - } - } - return distance; - } - -} +package org.graphast.query.route.shortestpath.dijkstra; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Set; + +import org.graphast.model.Edge; +import org.graphast.model.Graph; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; +import org.graphast.query.model.Bound; +import org.graphast.query.model.QueueEntry; +import org.graphast.query.route.shortestpath.model.RouteEntry; +import org.graphast.query.route.shortestpath.model.TimeEntry; + +import it.unimi.dsi.fastutil.longs.Long2DoubleMap; +import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2IntMap; +import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongSet; + +public class DijkstraLinearFunction extends Dijkstra { + + public DijkstraLinearFunction(Graph graph) { + super(graph); + } + + public DijkstraLinearFunction(GraphBounds graphBounds) { + super(graphBounds); + } + + public void expandVertex(Node target, TimeEntry removed, HashMap wasTraversed, Set allWasViseted, + PriorityQueue queue, HashMap parents){ + + HashMap neighbors = graph.accessNeighborhood(graph.getNode(removed.getId()), removed.getArrivalTime()); + + for (Node node : neighbors.keySet()) { + long vid = node.getId(); + allWasViseted.add(vid); + int at = graph.getArrival(removed.getArrivalTime(), neighbors.get(node)); + int tt = removed.getTravelTime() + neighbors.get(node); + TimeEntry newEntry = new TimeEntry( vid, tt, at, removed.getId()); + + Edge edge = null; + int distance = -1; + + if(!wasTraversed.containsKey(vid)){ + queue.offer(newEntry); + wasTraversed.put(newEntry.getId(), newEntry.getTravelTime()); + + distance = neighbors.get(node); + edge = getEdge(removed.getId(), vid, distance); + parents.put(vid, new RouteEntry(removed.getId(), distance, edge.getId(), edge.getLabel())); + }else{ + int cost = wasTraversed.get(vid); + if(cost != wasRemoved){ + if(cost>newEntry.getTravelTime()){ + queue.remove(newEntry); + queue.offer(newEntry); + long idNewEntry = newEntry.getId(); + wasTraversed.remove(idNewEntry); + wasTraversed.put(idNewEntry, newEntry.getTravelTime()); + + parents.remove(node); + distance = neighbors.get(node); + edge = getEdge(removed.getId(), vid, distance); + parents.put(vid, new RouteEntry(removed.getId(), distance, edge.getId(), edge.getLabel())); + } + } + } + } + } + + private Edge getEdge(long fromNodeId, long toNodeId, int distance) { + Edge edge = null; + for(Long outEdge : graph.getOutEdges(fromNodeId)) { + edge = graph.getEdge(outEdge); + if ((int) edge.getToNode() == toNodeId && edge.getDistance() == distance) { + break; + } + } + return edge; + } + + public List shortestPathCategories(long nodeId, Set categoriesIds, short graphType){ + + //TODO Change this PriorityQueue to some FastUtil structure + PriorityQueue unsettledNodes = new PriorityQueue(); + + LongSet settledNodes = new LongOpenHashSet(); + Long2IntMap shortestDistances = new Long2IntOpenHashMap(); + + Map bounds = new HashMap(); + int upper = Integer.MIN_VALUE; + int waitingTime, timeToService; + + shortestDistances.put(nodeId, 0); + + /* + * This queryEntry represents the travel time from this nodeId to + * another vertex (this vertex can be, for example, a PoI. In this + * way, the queryEntry is going to represent the travel time from + * the nodeId to a PoI.). + */ + QueueEntry queryEntry = new QueueEntry(nodeId, 0); + unsettledNodes.add(queryEntry); + + while ((queryEntry = unsettledNodes.poll()) != null){ + + if(bounds.keySet().containsAll(categoriesIds) && queryEntry.getTravelTime() > upper){ + // Use ArrayList because bounds.values() is not Serializable + return new ArrayList(bounds.values()); + } + + if(!settledNodes.contains(queryEntry.getId())) { + + settledNodes.add(queryEntry.getId()); + + Node poi = graphBounds.getPoi(queryEntry.getId()); + + if(poi != null) { + + int cat = poi.getCategory(); + + waitingTime = graphBounds.poiGetCost(queryEntry.getId(), graphType); + timeToService = queryEntry.getTravelTime() + waitingTime; + + if(bounds.keySet().contains(cat)) { + + int cost = bounds.get(cat).getCost(); + + if(timeToService < cost) bounds.put(cat, new Bound(queryEntry.getId(), timeToService)); +// if(timeToService < cost) bounds.put(e.getId(), new Bound(e.getId(), timeToService)); + upper = updateUpper(bounds); + + } else { + + bounds.put(cat, new Bound(queryEntry.getId(), timeToService)); + if(timeToService > upper) upper = timeToService; + + } + } + + expandVertex(queryEntry, settledNodes, shortestDistances, unsettledNodes, graphType); + + } + } + + // Use ArrayList because bounds.values() is not Serializable + return new ArrayList(bounds.values()); + } + + public int updateUpper(Map bounds){ + int upper = Integer.MIN_VALUE; + for(Bound b: bounds.values()){ + if(b.getCost() > upper) upper = b.getCost(); + } + return upper; + } + + public void expandVertex(QueueEntry e, LongSet settledNodes, Long2IntMap shortestDistances, + PriorityQueue unsettledNodes){ + + expandVertex(e, settledNodes, shortestDistances, unsettledNodes, (short) 0); + + } + + public void expandVertex(QueueEntry e, LongSet settledNodes, Long2IntMap shortestDistances, + PriorityQueue unsettledNodes, short graphType){ + + Long2IntMap adjacents = graphBounds.accessNeighborhood(graphBounds.getNode(e.getId()), graphType, 0); + + if(adjacents != null) { + + for (long v : adjacents.keySet()) { + + long nodeId = v; + + if (settledNodes.contains(nodeId)) continue; + + int shortDist = getShortestDistance(e.getId(), shortestDistances) + adjacents.get(v); + + if (shortDist < getShortestDistance(nodeId, shortestDistances)) + { + // assign new shortest distance and mark unsettled + + QueueEntry eNew = new QueueEntry(nodeId, shortDist); + unsettledNodes.remove(eNew); + unsettledNodes.add(eNew); + shortestDistances.put(nodeId, shortDist); + } + } + } + } + + public int getShortestDistance(long id, Long2IntMap minCost) + { + if(minCost.containsKey(id)) + return minCost.get(id); + else + return Integer.MAX_VALUE; + } + + public Long2DoubleMap shortestPath(long v){ + PriorityQueue unsettledNodes = new PriorityQueue(); + LongSet settledNodes = new LongOpenHashSet(); + Long2IntMap shortestDistances = new Long2IntOpenHashMap(); + Long2DoubleMap distance = new Long2DoubleOpenHashMap(); + + shortestDistances.put(v, 0); + distance.put(v, 0); + QueueEntry e = new QueueEntry(v, 0); + unsettledNodes.add(e); + + while ((e = unsettledNodes.poll()) != null){ + if(!settledNodes.contains(e.getId())){ + settledNodes.add(e.getId()); + distance.put(e.getId(), e.getTravelTime()); + + expandVertex(e, settledNodes, shortestDistances, unsettledNodes, (short)0); + } + } + return distance; + } + +} diff --git a/core/src/main/java/org/graphast/query/route/shortestpath/model/Path.java b/core/src/main/java/org/graphast/query/route/shortestpath/model/Path.java index 396a765..d19c16d 100644 --- a/core/src/main/java/org/graphast/query/route/shortestpath/model/Path.java +++ b/core/src/main/java/org/graphast/query/route/shortestpath/model/Path.java @@ -1,331 +1,341 @@ -package org.graphast.query.route.shortestpath.model; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -import org.graphast.geometry.PoI; -import org.graphast.geometry.Point; -import org.graphast.model.Edge; -import org.graphast.model.Graph; -import org.graphast.query.route.osr.Sequence; -import org.graphast.query.route.shortestpath.AbstractShortestPathService; -import org.graphast.query.route.shortestpath.dijkstra.DijkstraLinearFunction; -import org.graphast.util.DistanceUtils; - -public class Path { - - private List geometry; - private List edges; - private List instructions; - private List listOfPoIs; - private long totalDistance; - private double totalCost; - - public Path() { - - } - - - //TODO MAJOR REFACTOR NEEDED IN THIS METHOD! - public void constructPath(long id, HashMap parents, Graph graph) { - Instruction oldInstruction, newInstruction; - LinkedList verificationQueue = new LinkedList(); - if (parents.get(id) == null) { - instructions = new ArrayList(); - newInstruction = new Instruction(0, "On Start", 0, 0); - instructions.add(newInstruction); - return; - } - RouteEntry re = parents.get(id); - - long parent = re.getId(); - - instructions = new ArrayList(); - edges = new ArrayList(); - geometry = new ArrayList(); - - List listOfGeometries; - - Edge newEdge; - - if(re.getEdgeId()!=-1) { - newEdge = graph.getEdge(re.getEdgeId()); - newInstruction = new Instruction(0, re.getLabel(), re.getCost(), newEdge.getDistance()); - edges.add(re.getEdgeId()); - - if (newEdge.getGeometry() != null) { - - listOfGeometries = graph.getEdge(re.getEdgeId()).getGeometry(); - - if(DistanceUtils.distanceLatLong(listOfGeometries.get(0).getLatitude(), listOfGeometries.get(0).getLongitude(), graph.getNode(graph.getEdge(re.getEdgeId()).getFromNode()).getLatitude(), graph.getNode(graph.getEdge(re.getEdgeId()).getFromNode()).getLongitude()) > 0) { - Collections.reverse(listOfGeometries); - } - - - Collections.reverse(listOfGeometries); - newInstruction.setStartGeometry(geometry.size()); - - for (Point point : listOfGeometries) { - if(geometry.contains(point)) { - continue; - } else { - geometry.add(point); - } - } - newInstruction.setEndGeometry(geometry.size()-1); - } - } else { - newInstruction = new Instruction(0, re.getLabel(), re.getCost(), 0); - edges.add(re.getEdgeId()); - } - - - - verificationQueue.add(newInstruction); - - while (parent != -1) { - re = parents.get(parent); - - if (re != null) { - String predecessorLabel = verificationQueue.peek().getLabel(); - if(re.getEdgeId()!=-1) { - newEdge = graph.getEdge(re.getEdgeId()); - } else { - newEdge = null; - } - if ((predecessorLabel == null && re.getLabel() == null) - || (predecessorLabel != null && predecessorLabel.equals(re.getLabel())) - || (predecessorLabel != null && (predecessorLabel.isEmpty() && re.getLabel() == null))) { - oldInstruction = verificationQueue.poll(); - if(re.getEdgeId()!=-1) { - newInstruction = new Instruction(0, oldInstruction.getLabel(), - oldInstruction.getCost() + re.getCost(), oldInstruction.getDistance() + newEdge.getDistance()); - } else { - newInstruction = new Instruction(0, oldInstruction.getLabel(), - oldInstruction.getCost() + re.getCost(), 0); - } - newInstruction.setStartGeometry(oldInstruction.getStartGeometry()); - } else { - if(re.getEdgeId()!=-1) { - newInstruction = new Instruction(0, re.getLabel(), re.getCost(), newEdge.getDistance()); - } else { - newInstruction = new Instruction(0, re.getLabel(), re.getCost(), 0); - } - newInstruction.setStartGeometry(geometry.size()-1); - } - edges.add(re.getEdgeId()); - - if(re.getEdgeId()!=-1) { - if (newEdge.getGeometry() != null) { - - listOfGeometries = graph.getEdge(re.getEdgeId()).getGeometry(); - - if(geometry.size()!=0) { - if(DistanceUtils.distanceLatLong(listOfGeometries.get(0).getLatitude(), listOfGeometries.get(0).getLongitude(), geometry.get(geometry.size()-1).getLatitude(), geometry.get(geometry.size()-1).getLongitude()) > - DistanceUtils.distanceLatLong(listOfGeometries.get(listOfGeometries.size()-1).getLatitude(), listOfGeometries.get(listOfGeometries.size()-1).getLongitude(), geometry.get(geometry.size()-1).getLatitude(), geometry.get(geometry.size()-1).getLongitude()) ) { - Collections.reverse(listOfGeometries); - } - } - - for (Point point : listOfGeometries) { - if(geometry.contains(point)) { - // if(previousLatitude==point.getLatitude() && previousLongitude==point.getLongitude()) { - continue; - } else { - geometry.add(point); - } - } - } - newInstruction.setEndGeometry(geometry.size()-1); - } - - verificationQueue.addFirst(newInstruction); - parent = re.getId(); - } else { - break; - } - } - - Collections.reverse(edges); - Collections.reverse(geometry); - while (!verificationQueue.isEmpty()) { - instructions.add(verificationQueue.poll()); - } - Collections.reverse(instructions); - } - - - - public static Path pathsConcatanation(List paths) { - - Path path = new Path(); - - List temporaryGeometry = new ArrayList(); - List temporaryEdges = new ArrayList(); - List temporaryInstructions = new ArrayList(); - List temporaryListOfPoIs = new ArrayList(); - long temporaryTotalDistance = 0; - double temporaryTotalCost = 0; - - for(Path currentPath : paths) { - - for(Instruction instruction : currentPath.getInstructions()) { - - instruction.setStartGeometry(instruction.getStartGeometry() + temporaryGeometry.size()); - instruction.setEndGeometry(instruction.getEndGeometry() + temporaryGeometry.size()); - - } - - temporaryInstructions.addAll(currentPath.getInstructions()); - - temporaryGeometry.addAll(currentPath.getGeometry()); - temporaryEdges.addAll(currentPath.getEdges()); - - temporaryListOfPoIs.addAll(currentPath.getListOfPoIs()); - temporaryTotalDistance = temporaryTotalDistance + currentPath.getTotalDistance(); - temporaryTotalCost = temporaryTotalCost + currentPath.getTotalCost(); - - } - - - path.setGeometry(temporaryGeometry); - path.setEdges(temporaryEdges); - path.setInstructions(temporaryInstructions); - path.setListOfPoIs(temporaryListOfPoIs); - path.setTotalDistance(temporaryTotalDistance); - path.setTotalCost(temporaryTotalCost); - - return path; - - } - - public void setTotalDistance(long totalDistance) { - this.totalDistance = totalDistance; - } - - public void setTotalCost(double totalCost) { - this.totalCost = totalCost; - } - - public List getListOfPoIs() { - return listOfPoIs; - } - - public void setListOfPoIs(List listOfPoIs) { - this.listOfPoIs = listOfPoIs; - } - - public Path generatePath(double lat1, double lon1, double lat2, double lon2, Sequence sequence, Graph graph) { - List geometry = new ArrayList(); - List edges = new ArrayList(); - List instructions = new ArrayList(); - long inicioId = graph.getNodeId(lat1, lon1); - AbstractShortestPathService sp = new DijkstraLinearFunction(graph); - for(int i = 0; i < sequence.getPois().size(); i++) { - Path partialPath = sp.shortestPath(inicioId, sequence.getPois().get(i).getId()); - if(inicioId != sequence.getPois().get(i).getId()) { - geometry.addAll(partialPath.getGeometry()); - edges.addAll(partialPath.getEdges()); - instructions.addAll(partialPath.getPath()); - } - inicioId = sequence.getPois().get(i).getId(); - } - Path partialPath = sp.shortestPath(inicioId, graph.getNodeId(lat2, lon2)); - if(inicioId != graph.getNodeId(lat2, lon2)) { - geometry.addAll(partialPath.getGeometry()); - edges.addAll(partialPath.getEdges()); - instructions.addAll(partialPath.getPath()); - } - Path path = new Path(); - path.setEdges(edges); - path.setGeometry(geometry); - path.setPath(instructions); - return path; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("\n"); - - Iterator instructionIterator = instructions.iterator(); - - while (instructionIterator.hasNext()) { - - Instruction instruction = instructionIterator.next(); - sb.append("("); - - sb.append(instruction.getDirection()).append(","); - sb.append(instruction.getLabel()).append(","); - sb.append(instruction.getCost()).append(","); - sb.append(instruction.getDistance()); - sb.append(")"); - sb.append("\n"); - - } - - return sb.toString(); - - } - - public List getPath() { - return instructions; - } - - public void setPath(List path) { - this.instructions = path; - } - - public List getEdges() { - return edges; - } - - public void setEdges(List edges) { - this.edges = edges; - } - - public List getInstructions() { - return instructions; - } - - - public void setInstructions(List instructions) { - this.instructions = instructions; - } - - - public List getGeometry() { - return geometry; - } - - public void setGeometry(List geometry) { - this.geometry = geometry; - } - - public long getTotalDistance() { - - totalDistance = 0; - - for (Instruction instruction : instructions) { - totalDistance = totalDistance + instruction.getDistance(); - } - - return totalDistance; - } - - public double getTotalCost() { - - totalCost = 0; - - for (Instruction instruction : instructions) { - totalCost = totalCost + instruction.getCost(); - } - return totalCost; - } - +package org.graphast.query.route.shortestpath.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.graphast.geometry.PoI; +import org.graphast.geometry.Point; +import org.graphast.model.Edge; +import org.graphast.model.Graph; +import org.graphast.query.route.osr.Sequence; +import org.graphast.query.route.shortestpath.AbstractShortestPathService; +import org.graphast.query.route.shortestpath.dijkstra.DijkstraLinearFunction; +import org.graphast.util.DistanceUtils; + +public class Path { + + private List geometry; + private List edges; + private List instructions; + private List listOfPoIs; + private long totalDistance; + private double totalCost; + private int numberVisitedNodes; + + public Path() { + + } + + + //TODO MAJOR REFACTOR NEEDED IN THIS METHOD! + public void constructPath(long id, HashMap parents, Graph graph) { + Instruction oldInstruction, newInstruction; + LinkedList verificationQueue = new LinkedList(); + if (parents.get(id) == null) { + instructions = new ArrayList(); + newInstruction = new Instruction(0, "On Start", 0, 0); + instructions.add(newInstruction); + return; + } + RouteEntry re = parents.get(id); + + long parent = re.getId(); + + instructions = new ArrayList(); + edges = new ArrayList(); + geometry = new ArrayList(); + + List listOfGeometries; + + Edge newEdge; + + if(re.getEdgeId()!=-1) { + newEdge = graph.getEdge(re.getEdgeId()); + newInstruction = new Instruction(0, re.getLabel(), re.getCost(), newEdge.getDistance()); + edges.add(re.getEdgeId()); + + if (newEdge.getGeometry() != null) { + + listOfGeometries = graph.getEdge(re.getEdgeId()).getGeometry(); + + if(DistanceUtils.distanceLatLong(listOfGeometries.get(0).getLatitude(), listOfGeometries.get(0).getLongitude(), graph.getNode(graph.getEdge(re.getEdgeId()).getFromNode()).getLatitude(), graph.getNode(graph.getEdge(re.getEdgeId()).getFromNode()).getLongitude()) > 0) { + Collections.reverse(listOfGeometries); + } + + + Collections.reverse(listOfGeometries); + newInstruction.setStartGeometry(geometry.size()); + + for (Point point : listOfGeometries) { + if(geometry.contains(point)) { + continue; + } else { + geometry.add(point); + } + } + newInstruction.setEndGeometry(geometry.size()-1); + } + } else { + newInstruction = new Instruction(0, re.getLabel(), re.getCost(), 0); + edges.add(re.getEdgeId()); + } + + + + verificationQueue.add(newInstruction); + + while (parent != -1) { + re = parents.get(parent); + + if (re != null) { + String predecessorLabel = verificationQueue.peek().getLabel(); + if(re.getEdgeId()!=-1) { + newEdge = graph.getEdge(re.getEdgeId()); + } else { + newEdge = null; + } + if ((predecessorLabel == null && re.getLabel() == null) + || (predecessorLabel != null && predecessorLabel.equals(re.getLabel())) + || (predecessorLabel != null && (predecessorLabel.isEmpty() && re.getLabel() == null))) { + oldInstruction = verificationQueue.poll(); + if(re.getEdgeId()!=-1) { + newInstruction = new Instruction(0, oldInstruction.getLabel(), + oldInstruction.getCost() + re.getCost(), oldInstruction.getDistance() + newEdge.getDistance()); + } else { + newInstruction = new Instruction(0, oldInstruction.getLabel(), + oldInstruction.getCost() + re.getCost(), 0); + } + newInstruction.setStartGeometry(oldInstruction.getStartGeometry()); + } else { + if(re.getEdgeId()!=-1) { + newInstruction = new Instruction(0, re.getLabel(), re.getCost(), newEdge.getDistance()); + } else { + newInstruction = new Instruction(0, re.getLabel(), re.getCost(), 0); + } + newInstruction.setStartGeometry(geometry.size()-1); + } + edges.add(re.getEdgeId()); + + if(re.getEdgeId()!=-1) { + if (newEdge.getGeometry() != null) { + + listOfGeometries = graph.getEdge(re.getEdgeId()).getGeometry(); + + if(geometry.size()!=0) { + if(DistanceUtils.distanceLatLong(listOfGeometries.get(0).getLatitude(), listOfGeometries.get(0).getLongitude(), geometry.get(geometry.size()-1).getLatitude(), geometry.get(geometry.size()-1).getLongitude()) > + DistanceUtils.distanceLatLong(listOfGeometries.get(listOfGeometries.size()-1).getLatitude(), listOfGeometries.get(listOfGeometries.size()-1).getLongitude(), geometry.get(geometry.size()-1).getLatitude(), geometry.get(geometry.size()-1).getLongitude()) ) { + Collections.reverse(listOfGeometries); + } + } + + for (Point point : listOfGeometries) { + if(geometry.contains(point)) { + // if(previousLatitude==point.getLatitude() && previousLongitude==point.getLongitude()) { + continue; + } else { + geometry.add(point); + } + } + } + newInstruction.setEndGeometry(geometry.size()-1); + } + + verificationQueue.addFirst(newInstruction); + parent = re.getId(); + } else { + break; + } + } + + Collections.reverse(edges); + Collections.reverse(geometry); + while (!verificationQueue.isEmpty()) { + instructions.add(verificationQueue.poll()); + } + Collections.reverse(instructions); + } + + + + public static Path pathsConcatanation(List paths) { + + Path path = new Path(); + + List temporaryGeometry = new ArrayList(); + List temporaryEdges = new ArrayList(); + List temporaryInstructions = new ArrayList(); + List temporaryListOfPoIs = new ArrayList(); + long temporaryTotalDistance = 0; + double temporaryTotalCost = 0; + + for(Path currentPath : paths) { + + for(Instruction instruction : currentPath.getInstructions()) { + + instruction.setStartGeometry(instruction.getStartGeometry() + temporaryGeometry.size()); + instruction.setEndGeometry(instruction.getEndGeometry() + temporaryGeometry.size()); + + } + + temporaryInstructions.addAll(currentPath.getInstructions()); + + temporaryGeometry.addAll(currentPath.getGeometry()); + temporaryEdges.addAll(currentPath.getEdges()); + + temporaryListOfPoIs.addAll(currentPath.getListOfPoIs()); + temporaryTotalDistance = temporaryTotalDistance + currentPath.getTotalDistance(); + temporaryTotalCost = temporaryTotalCost + currentPath.getTotalCost(); + + } + + + path.setGeometry(temporaryGeometry); + path.setEdges(temporaryEdges); + path.setInstructions(temporaryInstructions); + path.setListOfPoIs(temporaryListOfPoIs); + path.setTotalDistance(temporaryTotalDistance); + path.setTotalCost(temporaryTotalCost); + + return path; + + } + + public void setTotalDistance(long totalDistance) { + this.totalDistance = totalDistance; + } + + public void setTotalCost(double totalCost) { + this.totalCost = totalCost; + } + + public List getListOfPoIs() { + return listOfPoIs; + } + + public void setListOfPoIs(List listOfPoIs) { + this.listOfPoIs = listOfPoIs; + } + + public Path generatePath(double lat1, double lon1, double lat2, double lon2, Sequence sequence, Graph graph) { + List geometry = new ArrayList(); + List edges = new ArrayList(); + List instructions = new ArrayList(); + long inicioId = graph.getNodeId(lat1, lon1); + AbstractShortestPathService sp = new DijkstraLinearFunction(graph); + for(int i = 0; i < sequence.getPois().size(); i++) { + Path partialPath = sp.shortestPath(inicioId, sequence.getPois().get(i).getId()); + if(inicioId != sequence.getPois().get(i).getId()) { + geometry.addAll(partialPath.getGeometry()); + edges.addAll(partialPath.getEdges()); + instructions.addAll(partialPath.getPath()); + } + inicioId = sequence.getPois().get(i).getId(); + } + Path partialPath = sp.shortestPath(inicioId, graph.getNodeId(lat2, lon2)); + if(inicioId != graph.getNodeId(lat2, lon2)) { + geometry.addAll(partialPath.getGeometry()); + edges.addAll(partialPath.getEdges()); + instructions.addAll(partialPath.getPath()); + } + Path path = new Path(); + path.setEdges(edges); + path.setGeometry(geometry); + path.setPath(instructions); + return path; + } + + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + sb.append("\n"); + + Iterator instructionIterator = instructions.iterator(); + + while (instructionIterator.hasNext()) { + + Instruction instruction = instructionIterator.next(); + sb.append("("); + + sb.append(instruction.getDirection()).append(","); + sb.append(instruction.getLabel()).append(","); + sb.append(instruction.getCost()).append(","); + sb.append(instruction.getDistance()); + sb.append(")"); + sb.append("\n"); + + } + + return sb.toString(); + + } + + public List getPath() { + return instructions; + } + + public void setPath(List path) { + this.instructions = path; + } + + public List getEdges() { + return edges; + } + + public void setEdges(List edges) { + this.edges = edges; + } + + public List getInstructions() { + return instructions; + } + + + public void setInstructions(List instructions) { + this.instructions = instructions; + } + + + public List getGeometry() { + return geometry; + } + + public void setGeometry(List geometry) { + this.geometry = geometry; + } + + public long getTotalDistance() { + + totalDistance = 0; + + for (Instruction instruction : instructions) { + totalDistance = totalDistance + instruction.getDistance(); + } + + return totalDistance; + } + + public double getTotalCost() { + + totalCost = 0; + + for (Instruction instruction : instructions) { + totalCost = totalCost + instruction.getCost(); + } + return totalCost; + } + + + public int getNumberVisitedNodes() { + return numberVisitedNodes; + } + + + public void setNumberVisitedNodes(int numberVisitedNodes) { + this.numberVisitedNodes = numberVisitedNodes; + } } \ No newline at end of file diff --git a/core/src/main/java/org/graphast/util/BenchmarkMemory.java b/core/src/main/java/org/graphast/util/BenchmarkMemory.java new file mode 100644 index 0000000..4cfc65a --- /dev/null +++ b/core/src/main/java/org/graphast/util/BenchmarkMemory.java @@ -0,0 +1,169 @@ +package org.graphast.util; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class BenchmarkMemory { + + private static final String PATTERN_SEPARATOR = ":"; + private static final String PATTERN_NUMBER = "-?\\d+"; + + public static Map quantityMemory() throws IOException { + + final String COMMAND_MEMORY = "egrep --color 'Mem|Cache|Swap' /proc/meminfo\n"; + final String COMMAND_EXIT = "exit\n"; + + Process telnetProcess = createProcessBuilder(); + BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream())); + BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream())); + runCommand(COMMAND_MEMORY, output); + runCommand(COMMAND_EXIT, output); + + return runPatter(input); + } + + //cat /proc/10925/io + + public static Long ioProcess(int pid, PROCESS process) throws IOException { + + final String COMMAND_PROCESS = "cat /proc/"+pid+"/io \n"; + final String COMMAND_EXIT = "exit\n"; + + Process telnetProcess = createProcessBuilder(); + BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream())); + BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream())); + runCommand(COMMAND_PROCESS, output); + runCommand(COMMAND_EXIT, output); + + Map runPatterIO = runPatterIO(input); + Long read_byte = runPatterIO.get("rchar"); + Long write_byte = runPatterIO.get("wchar"); + + if(read_byte != null && write_byte != null) { + if(process.equals(PROCESS.READ)) { + return read_byte; + } else { + return write_byte; + } + } + return 0l; + } + + private static Map runPatterIO(BufferedReader input) throws NumberFormatException, IOException { + + Map listMemory = new HashMap(); + String line; + + while ((line = input.readLine()) != null) { + + String[] split = line.split(PATTERN_SEPARATOR); + String keyIOProcess = split[0]; + String x2 = split[1]; + Matcher matcher = Pattern.compile(PATTERN_NUMBER).matcher(x2); + Long value = 0l; + + while (matcher.find()) { + value = Long.valueOf(matcher.group()); + } + + listMemory.put(keyIOProcess, value); + } + + return listMemory; + } + + public enum PROCESS { + READ, + WRITE + } + + public static List listIdProcess() throws IOException { + + final String COMMAND_PROCESS = "ps -ax | grep java\n"; + final String COMMAND_EXIT = "exit\n"; + + Process telnetProcess = createProcessBuilder(); + BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream())); + BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream())); + runCommand(COMMAND_PROCESS, output); + runCommand(COMMAND_EXIT, output); + + return runPatterProcess(input); + } + + private static List runPatterProcess(BufferedReader input) throws IOException { + + List listProcess = new ArrayList(); + String line; + + while ((line = input.readLine()) != null) { + String[] PID = line.split(" "); + if(org.apache.commons.lang3.StringUtils.isNumeric(PID[0])) { + listProcess.add(Integer.valueOf(PID[0])); + } + } + + return listProcess; + } + + private static Map runPatter(BufferedReader input) throws IOException { + + Map listMemory = new HashMap(); + String line; + + while ((line = input.readLine()) != null) { + + String[] split = line.split(PATTERN_SEPARATOR); + String keyMemory = split[0]; + String x2 = split[1]; + Matcher matcher = Pattern.compile(PATTERN_NUMBER).matcher(x2); + Long value = 0l; + + while (matcher.find()) { + value = Long.valueOf(matcher.group()); + } + + listMemory.put(keyMemory, value); + } + + return listMemory; + } + + private static Process createProcessBuilder() throws IOException { + + ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash"); + processBuilder.redirectErrorStream(true); + Process telnetProcess = processBuilder.start(); + return telnetProcess; + } + + private static void runCommand(final String command, BufferedWriter output) throws IOException { + output.write(command); + output.flush(); + } + + public static long getUsedMemory() { + + Runtime.getRuntime().gc(); + long numberUseMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); + return numberUseMemory; + } + + public static void main(String[] args) throws IOException { + + List listIdProcess = BenchmarkMemory.listIdProcess(); + for (Integer integer : listIdProcess) { + System.out.println(BenchmarkMemory.ioProcess(integer, PROCESS.READ)); + System.out.println(BenchmarkMemory.ioProcess(integer, PROCESS.WRITE)); + } + } +} diff --git a/core/src/main/java/org/graphast/util/ConnectionJDBC.java b/core/src/main/java/org/graphast/util/ConnectionJDBC.java new file mode 100644 index 0000000..1d997f7 --- /dev/null +++ b/core/src/main/java/org/graphast/util/ConnectionJDBC.java @@ -0,0 +1,38 @@ +package org.graphast.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Properties; + +public class ConnectionJDBC { + + private static Connection connection = null; + private static final String FILE_NAME_PROPERTIES = "db.properties"; + private static final String STR_DRIVER = "driver"; + private static final String STR_HOST = "host"; + private static final String STR_USER = "user"; + private static final String STR_PASS = "password"; + + + public static Connection getConnection() throws ClassNotFoundException, + SQLException, IOException { + + if (connection == null || connection.isClosed()) { + + Properties properties = new Properties(); + properties.load(new FileInputStream(new File(FILE_NAME_PROPERTIES))); + Class.forName(properties.getProperty(STR_DRIVER)); + String host = properties.getProperty(STR_HOST); + String user = properties.getProperty(STR_USER); + String password = properties.getProperty(STR_PASS); + + connection = DriverManager.getConnection(host, user, password); + } + + return connection; + } +} diff --git a/core/src/main/java/org/graphast/util/GeoUtils.java b/core/src/main/java/org/graphast/util/GeoUtils.java index da91e13..2c7c48d 100644 --- a/core/src/main/java/org/graphast/util/GeoUtils.java +++ b/core/src/main/java/org/graphast/util/GeoUtils.java @@ -1,93 +1,103 @@ -package org.graphast.util; - -public class GeoUtils { - - final private static double R_MAJOR = 6378137.0; - final private static double R_MINOR = 6356752.3142; - - /** - * Factor used to convert and round latitude and longitude to/from int. - */ - public static int LAT_LONG_CONVERTION_FACTOR = 1000000; - - - public GeoUtils() { - } - - public static int latLongToInt(double number) { - return (int) NumberUtils.convert(number, LAT_LONG_CONVERTION_FACTOR); - } - - public static double latLongToDouble(int number) { - return number / (double) LAT_LONG_CONVERTION_FACTOR; - } - - public static String long2XSpherical(String number) { - try { - double d = Double.parseDouble(number); - return String.valueOf(long2XSpherical(d)); - } catch (Exception e) { - throw new IllegalArgumentException("Could not convert " + number + " to double.", e); - } - } - - public static String lat2YSpherical(String number) { - try { - double d = Double.parseDouble(number); - return String.valueOf(lat2YSpherical(d)); - } catch (Exception e) { - throw new IllegalArgumentException("Could not convert " + number + " to double.", e); - } - } - - /** - * - * @param longitude in degrees - * @return X offset from your original position in meters. - */ - public static double long2XSpherical(double longitude) { - return 6378137 * Math.toRadians(longitude); - } - - /** - * - * @param latitude in degrees - * @return Y offset from your original position in meters. - */ - public static double lat2YSpherical(double latitude) { - return 6378137 * Math.log(Math.tan(Math.PI / 4 + Math.toRadians(latitude) / 2.0)); - } - - public static double x2LongSpherical(double x) { - return Math.toDegrees(x / 6378137.0); - } - - public static double y2LatSpherical(double y) { - return Math.toDegrees(Math.atan(Math.sinh(y / 6378137))); - } - - public static double long2XElliptical(double lon) { - return R_MAJOR * Math.toRadians(lon); - } - - public static double lat2YElliptical(double lat) { - if (lat > 89.5) { - lat = 89.5; - } - if (lat < -89.5) { - lat = -89.5; - } - double temp = R_MINOR / R_MAJOR; - double es = 1.0 - (temp * temp); - double eccent = Math.sqrt(es); - double phi = Math.toRadians(lat); - double sinphi = Math.sin(phi); - double con = eccent * sinphi; - double com = 0.5 * eccent; - con = Math.pow(((1.0-con)/(1.0+con)), com); - double ts = Math.tan(0.5 * ((Math.PI*0.5) - phi))/con; - double y = 0 - R_MAJOR * Math.log(ts); - return y; - } - -} +package org.graphast.util; + +import org.graphast.model.Edge; +import org.graphast.model.GraphBounds; +import org.graphast.model.Node; + +public class GeoUtils { + + final private static double R_MAJOR = 6378137.0; + final private static double R_MINOR = 6356752.3142; + + /** + * Factor used to convert and round latitude and longitude to/from int. + */ + public static int LAT_LONG_CONVERTION_FACTOR = 1000000; + + + public GeoUtils() { + } + + public static int latLongToInt(double number) { + return (int) NumberUtils.convert(number, LAT_LONG_CONVERTION_FACTOR); + } + + public static double latLongToDouble(int number) { + return number / (double) LAT_LONG_CONVERTION_FACTOR; + } + + public static String long2XSpherical(String number) { + try { + double d = Double.parseDouble(number); + return String.valueOf(long2XSpherical(d)); + } catch (Exception e) { + throw new IllegalArgumentException("Could not convert " + number + " to double.", e); + } + } + + public static String lat2YSpherical(String number) { + try { + double d = Double.parseDouble(number); + return String.valueOf(lat2YSpherical(d)); + } catch (Exception e) { + throw new IllegalArgumentException("Could not convert " + number + " to double.", e); + } + } + + /** + * + * @param longitude in degrees + * @return X offset from your original position in meters. + */ + public static double long2XSpherical(double longitude) { + return 6378137 * Math.toRadians(longitude); + } + + /** + * + * @param latitude in degrees + * @return Y offset from your original position in meters. + */ + public static double lat2YSpherical(double latitude) { + return 6378137 * Math.log(Math.tan(Math.PI / 4 + Math.toRadians(latitude) / 2.0)); + } + + public static double x2LongSpherical(double x) { + return Math.toDegrees(x / 6378137.0); + } + + public static double y2LatSpherical(double y) { + return Math.toDegrees(Math.atan(Math.sinh(y / 6378137))); + } + + public static double long2XElliptical(double lon) { + return R_MAJOR * Math.toRadians(lon); + } + + public static double lat2YElliptical(double lat) { + if (lat > 89.5) { + lat = 89.5; + } + if (lat < -89.5) { + lat = -89.5; + } + double temp = R_MINOR / R_MAJOR; + double es = 1.0 - (temp * temp); + double eccent = Math.sqrt(es); + double phi = Math.toRadians(lat); + double sinphi = Math.sin(phi); + double con = eccent * sinphi; + double com = 0.5 * eccent; + con = Math.pow(((1.0-con)/(1.0+con)), com); + double ts = Math.tan(0.5 * ((Math.PI*0.5) - phi))/con; + double y = 0 - R_MAJOR * Math.log(ts); + return y; + } + + public static boolean isPointInEdgeLine(GraphBounds graph, Node point, Edge edge) { + Node start = graph.getNode(edge.getFromNode()); + Node end = graph.getNode(edge.getToNode()); + return DistanceUtils.distanceLatLong(start, point)+DistanceUtils.distanceLatLong(point, end)-DistanceUtils.distanceLatLong(start, end)<=0.1; + } + +} diff --git a/core/src/main/java/org/graphast/util/NumberUtils.java b/core/src/main/java/org/graphast/util/NumberUtils.java index f19eea8..1cb6b78 100755 --- a/core/src/main/java/org/graphast/util/NumberUtils.java +++ b/core/src/main/java/org/graphast/util/NumberUtils.java @@ -1,116 +1,121 @@ -package org.graphast.util; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -import org.graphast.exception.GraphastException; - -public class NumberUtils { - - public final static int SEGMENT_SHIFT = 14; - - public final static int SEGMENT_SIZE = 1 << SEGMENT_SHIFT; - - public final static int SEGMENT_MASK = SEGMENT_SIZE - 1; - - /** - * Returns a numeric value rounded to a specified number of digits. - * Negative decimals indicates the number of digits to the left of the - * decimal point to round. For example: - *
-     * NumberUtils.round(10.4, 0)                // Result: 10.0
-     * NumberUtils.round(10.5, 0)                // Result: 11.0
-     * NumberUtils.round(-10.5, 0)               // Result: -11.0
-     * NumberUtils.round(10.51, 0)               // Result: 11.0
-     * NumberUtils.round(10.49999999999999, 2)   // Result: 10.5
-     * 
- * Digits between five to nine, inclusive, are rounded up. Digits below - * five are rounded down. - * @param number the numeric value to round. - * @param decimals defines the number of decimal places to retain. - * @return the numeric value rounded to a specified number of digits. - */ - public static double round(double number, int decimals) { - double factor = (int)Math.pow(10, decimals); - number = number * factor; - if (number > 0) { - number = Math.round(number); - } else { - number = -Math.round(-number); - } - return number / factor; - } - - /** - * Returns a numeric value rounded to a specified number of digits. - * Negative decimals indicates the number of digits to the left of the - * decimal point to round. For example: - *
-     * NumberUtils.round(10.4, 0)                // Result: 10.0
-     * NumberUtils.round(10.5, 0)                // Result: 11.0
-     * NumberUtils.round(-10.5, 0)               // Result: -11.0
-     * NumberUtils.round(10.51, 0)               // Result: 11.0
-     * NumberUtils.round(10.49999999999999, 2)   // Result: 10.5
-     * 
- * Digits between five to nine, inclusive, are rounded up. Digits below - * five are rounded down. - * @param number the numeric value to round. - * @param decimals defines the number of decimal places to retain. - * @return the numeric value rounded to a specified number of digits. - */ - public static BigDecimal round(BigDecimal number, int decimals) { - return number.setScale(decimals, RoundingMode.HALF_UP); - } - - public static long convert(double number, int factor) { - number = number * factor; - if (number > 0) { - number = Math.round(number); - } else { - number = -Math.round(-number); - } - return (long)number; - } - - public static int convertToInt(Object obj){ - if(obj instanceof Long){ - return (int) ((long) obj); - }else if(obj instanceof String){ - return Integer.parseInt((String) obj); - }else{ - throw new GraphastException("Can not convert to int type"); - } - } - - /** - * Returns the segment part (a 'short' number) of a passed 'int' number. - * - * @param number an 'int' number to be segmented - * @return the segment part (a 'short' number) of the passed 'int' - */ - public static short segment(int number) { - return (short)(number >> 16); - } - - /** - * Returns the displacement part (a 'short' number) of a passed 'int' number. - * - * @param number an 'int' number to be 'displacemented' - * @return the displacement part (a 'short' number) of the passed 'int' - */ - public static short displacement(int number ) { - return (short)number; - } - - /** - * Turns two 'short' type numbers (segment and displacement) into a new 'int' number. - * - * @param segment segment part of the new 'int' number that will be created - * @param displacement displacement part of the new 'int' number that will be created - * @return an 'int' number based on the segment and displacement passed - */ - public static int index( final short segment, final short displacement ) { - return (short)segment << 16 | displacement & 0xFFFF; - } - -} +package org.graphast.util; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.Random; + +import org.graphast.exception.GraphastException; + +public class NumberUtils { + + public final static int SEGMENT_SHIFT = 14; + + public final static int SEGMENT_SIZE = 1 << SEGMENT_SHIFT; + + public final static int SEGMENT_MASK = SEGMENT_SIZE - 1; + + /** + * Returns a numeric value rounded to a specified number of digits. + * Negative decimals indicates the number of digits to the left of the + * decimal point to round. For example: + *
+     * NumberUtils.round(10.4, 0)                // Result: 10.0
+     * NumberUtils.round(10.5, 0)                // Result: 11.0
+     * NumberUtils.round(-10.5, 0)               // Result: -11.0
+     * NumberUtils.round(10.51, 0)               // Result: 11.0
+     * NumberUtils.round(10.49999999999999, 2)   // Result: 10.5
+     * 
+ * Digits between five to nine, inclusive, are rounded up. Digits below + * five are rounded down. + * @param number the numeric value to round. + * @param decimals defines the number of decimal places to retain. + * @return the numeric value rounded to a specified number of digits. + */ + public static double round(double number, int decimals) { + double factor = (int)Math.pow(10, decimals); + number = number * factor; + if (number > 0) { + number = Math.round(number); + } else { + number = -Math.round(-number); + } + return number / factor; + } + + /** + * Returns a numeric value rounded to a specified number of digits. + * Negative decimals indicates the number of digits to the left of the + * decimal point to round. For example: + *
+     * NumberUtils.round(10.4, 0)                // Result: 10.0
+     * NumberUtils.round(10.5, 0)                // Result: 11.0
+     * NumberUtils.round(-10.5, 0)               // Result: -11.0
+     * NumberUtils.round(10.51, 0)               // Result: 11.0
+     * NumberUtils.round(10.49999999999999, 2)   // Result: 10.5
+     * 
+ * Digits between five to nine, inclusive, are rounded up. Digits below + * five are rounded down. + * @param number the numeric value to round. + * @param decimals defines the number of decimal places to retain. + * @return the numeric value rounded to a specified number of digits. + */ + public static BigDecimal round(BigDecimal number, int decimals) { + return number.setScale(decimals, RoundingMode.HALF_UP); + } + + public static long convert(double number, int factor) { + number = number * factor; + if (number > 0) { + number = Math.round(number); + } else { + number = -Math.round(-number); + } + return (long)number; + } + + public static int convertToInt(Object obj){ + if(obj instanceof Long){ + return (int) ((long) obj); + }else if(obj instanceof String){ + return Integer.parseInt((String) obj); + }else{ + throw new GraphastException("Can not convert to int type"); + } + } + + /** + * Returns the segment part (a 'short' number) of a passed 'int' number. + * + * @param number an 'int' number to be segmented + * @return the segment part (a 'short' number) of the passed 'int' + */ + public static short segment(int number) { + return (short)(number >> 16); + } + + /** + * Returns the displacement part (a 'short' number) of a passed 'int' number. + * + * @param number an 'int' number to be 'displacemented' + * @return the displacement part (a 'short' number) of the passed 'int' + */ + public static short displacement(int number ) { + return (short)number; + } + + /** + * Turns two 'short' type numbers (segment and displacement) into a new 'int' number. + * + * @param segment segment part of the new 'int' number that will be created + * @param displacement displacement part of the new 'int' number that will be created + * @return an 'int' number based on the segment and displacement passed + */ + public static int index( final short segment, final short displacement ) { + return (short)segment << 16 | displacement & 0xFFFF; + } + + public static double generatePdseurandom(int rangeMin, int rangeMax) { + return rangeMin + (rangeMax - rangeMin) * new Random().nextDouble(); + } + +} diff --git a/core/src/main/resources/log4j.properties b/core/src/main/resources/log4j.properties index 31249d0..790f3f2 100755 --- a/core/src/main/resources/log4j.properties +++ b/core/src/main/resources/log4j.properties @@ -1,27 +1,29 @@ -# Log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL -log4j.threshold=ALL -log4j.rootLogger=ALL, stdout, logfile - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%-5p %d [%c:%L] - %m%n -log4j.appender.stdout.threshold=DEBUG -#log4j.appender.stdout.threshold=INFO - -log4j.appender.logfile=org.apache.log4j.RollingFileAppender -log4j.appender.logfile.File=${user.home}/graphast.log -log4j.appender.logfile.MaxFileSize=1024KB -log4j.appender.logfile.MaxBackupIndex=5 -log4j.appender.logfile.layout=org.apache.log4j.PatternLayout -#log4j.appender.logfile.layout.ConversionPattern=%-5p %d [%c:%L] - %m%n -log4j.appender.logfile.layout.ConversionPattern=%m%n -log4j.appender.logfile.threshold=TRACE -#log4j.appender.logfile.threshold=INFO - -log4j.category.br.com.caelum.vraptor=INFO -log4j.category.org.springframework=WARN -log4j.category.org.apache=INFO -log4j.category.br.com.nex2me.mobme.network.road.model.RoadGraphAdapter=INFO -log4j.category.br.com.nex2me.mobme.core.model.GraphAdapter=INFO -log4j.category.com.thinkaurelius.titan=ERROR -log4j.category.org.apache.cassandra=ERROR \ No newline at end of file +# Log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL +log4j.threshold=ALL +log4j.rootLogger=ALL, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p %d [%c:%L] - %m%n +log4j.appender.stdout.threshold=DEBUG +#log4j.appender.stdout.threshold=INFO + +log4j.appender.logfile=org.apache.log4j.RollingFileAppender +log4j.appender.logfile.File=${user.home}/graphast.log +log4j.appender.logfile.MaxFileSize=1024KB +log4j.appender.logfile.MaxBackupIndex=5 +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +#log4j.appender.logfile.layout.ConversionPattern=%-5p %d [%c:%L] - %m%n +log4j.appender.logfile.layout.ConversionPattern=%m%n +log4j.appender.logfile.threshold=TRACE +#log4j.appender.logfile.threshold=INFO + +log4j.category.br.com.caelum.vraptor=INFO +log4j.category.org.springframework=WARN +log4j.category.org.apache=INFO +log4j.category.br.com.nex2me.mobme.network.road.model.RoadGraphAdapter=INFO +log4j.category.br.com.nex2me.mobme.core.model.GraphAdapter=INFO +log4j.category.com.thinkaurelius.titan=ERROR +log4j.category.org.apache.cassandra=ERROR + +log4j.category.org.graphast.importer.OSMDBImporter=ERROR \ No newline at end of file diff --git a/core/src/main/resources/piecewise.sql b/core/src/main/resources/piecewise.sql new file mode 100644 index 0000000..abf1a20 --- /dev/null +++ b/core/src/main/resources/piecewise.sql @@ -0,0 +1,15 @@ +-- Table: public.tester + +-- DROP TABLE public.tester; + +CREATE TABLE public.piecewise +( + edgeId double precision, + timeDay double precision, + totalTime double precision +) +WITH ( + OIDS=FALSE +); +ALTER TABLE public.tester + OWNER TO postgres; \ No newline at end of file diff --git a/core/src/test/java/org/graphast/graphgenerator/GraphGenerator.java b/core/src/test/java/org/graphast/graphgenerator/GraphGenerator.java index 92e57b5..0c76773 100644 --- a/core/src/test/java/org/graphast/graphgenerator/GraphGenerator.java +++ b/core/src/test/java/org/graphast/graphgenerator/GraphGenerator.java @@ -1,5 +1,6 @@ package org.graphast.graphgenerator; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -572,5 +573,512 @@ public Graph generateAndorra() { return graph; } + +public GraphBounds generateExampleTAXI() { + + GraphBounds graph = new GraphImpl(Configuration.USER_HOME + "/graphast/test/examplePoI"); + + Node node; + Edge edge; + + node = new NodeImpl(0l, 0.0d, 1.0d); + graph.addNode(node); + + node = new NodeImpl(1l, 0.0d, 10.0d); + int[] costs = new int[]{0}; + node.setCategory(1); + node.setLabel("TAXI I"); + node.setCosts(costs); + graph.addNode(node); + + node = new NodeImpl(2l, 0.0d, 20.0d); + graph.addNode(node); + + node = new NodeImpl(3l, 0.0d, 30.0d); + graph.addNode(node); + + node = new NodeImpl(4l, 0.0d, 40.0d); + costs = new int[]{0}; + node.setCategory(2); + node.setLabel("TAXI II"); + node.setCosts(costs); + graph.addNode(node); + + node = new NodeImpl(5l, 10.0d, 0.0d); + graph.addNode(node); + + node = new NodeImpl(6l, 10.0d, 10.0d); + graph.addNode(node); + + node = new NodeImpl(7l, 10.0d, 20.0d); + graph.addNode(node); + + node = new NodeImpl(8l, 10.0d, 30.0d); + graph.addNode(node); + + node = new NodeImpl(9l, 10.0d, 40.0d); + costs = new int[]{0}; + node.setCategory(3); + node.setLabel("TAXI III"); + node.setCosts(costs); + graph.addNode(node); + + //EDGES + + edge = new EdgeImpl(1l, 0l, 1l, 15); + int[] costsEdge1 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000}; + edge.setCosts(costsEdge1); + graph.addEdge(edge); + + edge = new EdgeImpl(2l, 1l, 2l, 15); + int[] costsEdge2 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge2); + graph.addEdge(edge); + + edge = new EdgeImpl(3l, 1l, 7l, 12); + int[] costsEdge3 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000}; + edge.setCosts(costsEdge3); + graph.addEdge(edge); + + edge = new EdgeImpl(4l, 2l, 3l, 10); + int[] costsEdge4 = new int[]{600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge4); + graph.addEdge(edge); + + edge = new EdgeImpl(5l, 3l, 4l, 12); + int[] costsEdge5 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000}; + edge.setCosts(costsEdge5); + graph.addEdge(edge); + + edge = new EdgeImpl(6l, 4l, 8l, 12); + int[] costsEdge6 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000}; + edge.setCosts(costsEdge6); + graph.addEdge(edge); + + edge = new EdgeImpl(7l, 4l, 9l, 12); + int[] costsEdge7 = new int[]{720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge7); + graph.addEdge(edge); + + edge = new EdgeImpl(8l, 5l, 0l, 12); + int[] costsEdge8 = new int[]{720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000}; + edge.setCosts(costsEdge8); + graph.addEdge(edge); + + edge = new EdgeImpl(9l, 6l, 5l, 15); + int[] costsEdge9 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge9); + graph.addEdge(edge); + + edge = new EdgeImpl(10l, 7l, 2l, 15); + int[] costsEdge10 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge10); + graph.addEdge(edge); + + edge = new EdgeImpl(11l, 7l, 6l, 12); + int[] costsEdge11 = new int[]{720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge11); + graph.addEdge(edge); + + edge = new EdgeImpl(12l, 8l, 7l, 12); + int[] costsEdge12 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000}; + edge.setCosts(costsEdge12); + graph.addEdge(edge); + + edge = new EdgeImpl(13l, 9l, 8l, 15); + int[] costsEdge13 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge13); + graph.addEdge(edge); + + graph.createBounds(); + + return graph; + } + + public GraphBounds generateExampleTaxi15to15minutes() { + + String separator = File.separator; + final String directory = Configuration.USER_HOME + separator + + "graphast" + separator + "test" +separator + "exampleTaxi"; + + GraphBounds graph = new GraphImpl(directory); + + graph.addNode(new NodeImpl(0l, 0.0d, 1.0d)); + + Node nodeCategory1 = new NodeImpl(1l, 0.0d, 10.0d); + int[] costs = new int[]{0}; + nodeCategory1.setCategory(1); + nodeCategory1.setLabel("TAXI I"); + nodeCategory1.setCosts(costs); + graph.addNode(nodeCategory1); + + graph.addNode(new NodeImpl(2l, 0.0d, 20.0d)); + graph.addNode(new NodeImpl(3l, 0.0d, 30.0d)); + + Node nodeCategory2 = new NodeImpl(4l, 0.0d, 40.0d); + costs = new int[]{0}; + nodeCategory2.setCategory(2); + nodeCategory2.setLabel("TAXI II"); + nodeCategory2.setCosts(costs); + graph.addNode(nodeCategory2); + + graph.addNode(new NodeImpl(5l, 10.0d, 0.0d)); + graph.addNode(new NodeImpl(6l, 10.0d, 10.0d)); + graph.addNode(new NodeImpl(7l, 10.0d, 20.0d)); + graph.addNode(new NodeImpl(8l, 10.0d, 30.0d)); + + Node nodeCategory3 = new NodeImpl(9l, 10.0d, 40.0d); + costs = new int[]{0}; + nodeCategory3.setCategory(3); + nodeCategory3.setLabel("TAXI III"); + nodeCategory3.setCosts(costs); + graph.addNode(nodeCategory3); + + //Edges com custo de 15 em 15 minutos + + Edge edge = new EdgeImpl(1l, 0l, 1l, 15); + int[] costsEdge1 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000,900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000,900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 1200000, + 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, 900000, 900000, + 900000, 900000, 900000}; + edge.setCosts(costsEdge1); + graph.addEdge(edge); + + edge = new EdgeImpl(2l, 1l, 2l, 15); + int[] costsEdge2 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge2); + graph.addEdge(edge); + + Edge edge1to7 = new EdgeImpl(3l, 1l, 7l, 12); + int[] costsEdge1To7 = new int[]{960000, 960000, 300000, 300000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 300000, 300000, 1800000, 720000, 720000, + 720000, 720000, 720000}; + edge1to7.setCosts(costsEdge1To7); + graph.addEdge(edge1to7); + + Edge edge7to1 = new EdgeImpl(3l, 7l, 1l, 12); + int[] costsEdge7to1 = new int[]{600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000}; + edge7to1.setCosts(costsEdge7to1); + graph.addEdge(edge7to1); + + edge = new EdgeImpl(4l, 2l, 3l, 10); + int[] costsEdge4 = new int[]{600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge4); + graph.addEdge(edge); + edge = new EdgeImpl(5l, 3l, 4l, 12); + int[] costsEdge5 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, + 720000, 720000, 720000, 720000}; + edge.setCosts(costsEdge5); + graph.addEdge(edge); + + edge = new EdgeImpl(6l, 4l, 8l, 12); + int[] costsEdge6 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, + 720000, 720000, 720000}; + edge.setCosts(costsEdge6); + graph.addEdge(edge); + + edge = new EdgeImpl(7l, 4l, 9l, 12); + int[] costsEdge7 = new int[]{720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1500000, 1500000, 1500000, 1500000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge7); + graph.addEdge(edge); + + edge = new EdgeImpl(8l, 5l, 0l, 12); + int[] costsEdge8 = new int[]{720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 1080000, 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, + 1080000, 600000, 600000, 600000, 600000, 600000}; + edge.setCosts(costsEdge8); + graph.addEdge(edge); + + Edge edge6to5 = new EdgeImpl(9l, 6l, 5l, 15); + int[] costsEdge6to5 = new int[]{900000, 900000, 960000, 960000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 1200000, 1200000, 1200000, 900000, 900000, 900000, 1500000, 1500000, 1500000, 1500000, + 900000, 900000, 900000, 900000, 900000}; + edge6to5.setCosts(costsEdge6to5); + graph.addEdge(edge6to5); + + Edge edge5to6 = new EdgeImpl(9l, 5l, 6l, 15); + int[] costsEdge5to6 = new int[]{600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, + 600000, 600000, 600000}; + edge5to6.setCosts(costsEdge5to6); + graph.addEdge(edge5to6); + + edge = new EdgeImpl(10l, 7l, 2l, 15); + int[] costsEdge10 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge10); + graph.addEdge(edge); + + edge = new EdgeImpl(11l, 7l, 6l, 12); + int[] costsEdge11 = new int[]{720000, 720000, 480000, 480000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 780000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 780000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 780000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 1080000, 1080000, 1080000, 600000, 600000, + 600000, 600000, 600000, 720000, 720000, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 1080000, + 1080000, 1080000, 600000, 600000, 600000, 1080000, 120000, 120000, 1080000, 600000, 600000, + 600000, 600000, 600000}; + edge.setCosts(costsEdge11); + graph.addEdge(edge); + + edge = new EdgeImpl(12l, 8l, 7l, 12); + int[] costsEdge12 = new int[]{720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 720000, 1320000, + 1320000, 1320000, 720000, 720000, 720000, 1800000, 1800000, 1800000, 1800000, 720000, 720000, + 720000, 720000, 720000}; + edge.setCosts(costsEdge12); + graph.addEdge(edge); + + edge = new EdgeImpl(13l, 9l, 8l, 15); + int[] costsEdge13 = new int[]{900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, 900000, + 900000, 900000, 900000, 900000, 900000, 900000}; + edge.setCosts(costsEdge13); + graph.addEdge(edge); + + graph.createBounds(); + + return graph; + } } \ No newline at end of file diff --git a/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTest.java b/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTest.java new file mode 100644 index 0000000..6632a6f --- /dev/null +++ b/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTest.java @@ -0,0 +1,216 @@ +package org.graphast.graphgenerator; + +import org.graphast.config.Configuration; +import org.graphast.model.GraphBounds; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +public class GraphGeneratorGridTest { + + private String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + @Test + public void gererateGraphSynthetic2x2() { + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, 2,2,0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(4, graph.getNumberOfNodes()); + Assert.assertEquals(8, graph.getNumberOfEdges()); + Assert.assertNotNull(graph.getEdgeCost(graph.getEdge(0), 0)); + } + + @Test + public void gererateGraphSynthetic4x4() { + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, 4,4, 0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(16, graph.getNumberOfNodes()); + Assert.assertEquals(48, graph.getNumberOfEdges()); + Assert.assertNotNull(graph.getEdgeCost(graph.getEdge(0), 0)); + } + + @Test + public void gererateGraphSynthetic5x5() { + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, 5,5, 0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), 25); + Assert.assertEquals(graph.getNumberOfEdges(), 80); + } + + @Test + public void gererateGraphSynthetic100x100() { + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, 100,100, 0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), 10000); + Assert.assertEquals(graph.getNumberOfEdges(), 39600); + } + + @Ignore + @Test + public void gererateGraphSyntheticLimit() { + + int comprimento = 992; + int altura = 992; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + } + + @Ignore + @Test + public void gererateGraphSyntheticLimitWithPoi() { + + int comprimento = 992; + int altura = 992; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 1); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + Assert.assertEquals(graph.getCategories().size(), 9840); + } + + @Test + @Ignore + public void gererateGraphSyntheticDifferentSize() { + + int comprimento = 3; + int altura = 2; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 0); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + } + + @Test + public void gererateGraphSyntheticWithPoiShort() { + + int comprimento = 4; + int altura = 4; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento, altura, 1); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getCategories().size(), 1); + } + + @Test + public void gererateGraphSyntheticWithPoi() { + + int comprimento = 10; + int altura = 10; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento, altura, 2); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getCategories().size(), 2); + } + + @Test + public void gererateGraphSyntheticMin() { + + int comprimento = 1; + int altura = 1; + int percentagemPoi = 1; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento, altura, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getCategories().size(), 1); + } + + // grafos para o teste do algoritmo ============= + + // 1k (1024 pontos) + @Test + public void gererateGraphSyntheticLimitWithPoi1k() { + + int comprimento = 32; + int altura = 32; + int qtdPoi = 10; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 1); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + Assert.assertEquals(graph.getCategories().size(), qtdPoi); + } + + // 10k (10000 pontos) + @Test + public void gererateGraphSyntheticLimitWithPoi10k() { + + int comprimento = 100; + int altura = 100; + int qtdPoi = 100; + int percentualPoi = 1; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, percentualPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(comprimento*altura, graph.getNumberOfNodes()); + Assert.assertEquals(2*altura*(2*(comprimento-1)), graph.getNumberOfEdges()); + Assert.assertEquals(qtdPoi, graph.getCategories().size()); + } + + // 100k (99856 pontos) + @Test + public void gererateGraphSyntheticLimitWithPoi100k() { + + int comprimento = 316; + int altura = 316; + int qtdPoi = 998; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 1); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + Assert.assertEquals(graph.getCategories().size(), qtdPoi); + } + + // 1G (1000000 pontos) + @Test + public void gererateGraphSyntheticLimitWithPoi1000k() { + + int comprimento = 1000; + int altura = 1000; + int qtdPoi = 10000; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, 1); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + Assert.assertEquals(graph.getNumberOfNodes(), comprimento*altura); + Assert.assertEquals(graph.getNumberOfEdges(), 2*altura*(2*(comprimento-1))); + Assert.assertEquals(graph.getCategories().size(), qtdPoi); + } + +} diff --git a/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTester.java b/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTester.java new file mode 100644 index 0000000..a7070f3 --- /dev/null +++ b/core/src/test/java/org/graphast/graphgenerator/GraphGeneratorGridTester.java @@ -0,0 +1,135 @@ +package org.graphast.graphgenerator; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.util.HashSet; +import java.util.Random; +import java.util.Set; + +import org.graphast.importer.CostGenerator; +import org.graphast.model.Edge; +import org.graphast.model.EdgeImpl; +import org.graphast.model.GraphBounds; +import org.graphast.model.GraphImpl; +import org.graphast.model.Node; +import org.graphast.model.NodeImpl; + +public class GraphGeneratorGridTester { + + private int width; + private int length; + private GraphBounds graph; + private double percentagemPoi; + private BigDecimal distance_largura; + private BigDecimal distance_altura; + + public GraphGeneratorGridTester(String pathGraph, int width, int length, double percentualPoi) { + this.width = width; + this.length = length; + this.percentagemPoi = percentualPoi; + this.graph = new GraphImpl(pathGraph); + + } + + public GraphGeneratorGridTester(String pathGraph, int size, double percentualPoi) { + this(pathGraph, size, size, percentualPoi); + } + + public void generateGraph() { + plotNodes(); + plotEdges(); + graph.createBounds(); + } + + private void plotNodes() { + + BigDecimal interador_largura = BigDecimal.valueOf(180).divide(BigDecimal.valueOf(width), 8, RoundingMode.HALF_UP); + BigDecimal interador_altura = BigDecimal.valueOf(180).divide(BigDecimal.valueOf(length), 8, RoundingMode.HALF_UP); + this.distance_largura = interador_largura; + this.distance_altura = interador_altura; + + Set listaIdsPoi = getListIdsPois(); + + Integer category = 0; + for (int i = 0; i < width; i++) { + BigDecimal latitude = interador_altura.multiply(BigDecimal.valueOf(i)).add(BigDecimal.valueOf(-90)); + for (int j = 0; j < length; j++) { + BigDecimal longitude = interador_largura.multiply(BigDecimal.valueOf(j)).add(BigDecimal.valueOf(-90));; + Node node = new NodeImpl(Long.valueOf(category), latitude.doubleValue(), longitude.doubleValue()); + if(listaIdsPoi.contains(category)) { + int[] costs = new int[]{0}; + node.setCategory(category); + node.setLabel("CATEGORY "+category); + node.setCosts(costs); + listaIdsPoi.remove(category); + } + graph.addNode(node); + category++; + } + } + } + + private Set getListIdsPois() { + + int quantidadeVerticesPoi = BigDecimal.valueOf(width).multiply(BigDecimal.valueOf(length)).multiply(BigDecimal.valueOf(percentagemPoi)).divide(BigDecimal.valueOf(100.0f), 8, RoundingMode.UP).intValue(); + + Set listIdPoi = new HashSet<>(); + do { + int rangeMax = width*length - 1; + Double idRandom = generatePdseurandom(0, rangeMax); + listIdPoi.add(idRandom.intValue()); + } while(listIdPoi.size() accessNeighborhood = graph.accessNeighborhood(node, 0); + int size = accessNeighborhood.size(); + //System.out.println(String.format("the node %s contens %s neighbors", i, size)); + System.out.println(String.format("%s,%s", i, size)); + + } + } + + @Test + public void costEdgeTest() { + OSMDBImporter importer = new OSMDBImporter("view_exp_1k", PATH_GRAPH); + GraphBounds graphBounds = importer.execute(); + + for (int i = 0; i < graphBounds.getNumberOfEdges() - 1; i++) { + Edge edge = graphBounds.getEdge(i); + Assert.assertEquals(96, edge.getCosts().length); + } + } + + @Test + public void createGraphTest10k() { + + OSMDBImporter importer = new OSMDBImporter("view_exp_10k", PATH_GRAPH); + GraphBounds graph = importer.execute(); + Assert.assertNotNull(graph); + Assert.assertEquals(73, graph.getCategories().size()); //77 + Assert.assertEquals(6870, graph.getNumberOfNodes()); //6947 + Assert.assertEquals(8334, graph.getNumberOfEdges()); // + + for (int i = 0; i < graph.getNumberOfNodes(); i++) { + Node node = graph.getNode(i); + HashMap accessNeighborhood = graph.accessNeighborhood(node, 0); + int size = accessNeighborhood.size(); + //System.out.println(String.format("the node %s contens %s neighbors", i, size)); + System.out.println(String.format("%s,%s", i, size)); + + } + } + + @Test + public void createGraphTest100k() { + OSMDBImporter importer = new OSMDBImporter("view_exp_100k", PATH_GRAPH); + GraphBounds graph = importer.execute(); + Assert.assertNotNull(graph); + Assert.assertEquals(379, graph.getCategories().size());//379 + Assert.assertEquals(75489, graph.getNumberOfNodes()); //75919 + Assert.assertEquals(98223, graph.getNumberOfEdges()); //98653 + + for (int i = 0; i < graph.getNumberOfNodes(); i++) { + Node node = graph.getNode(i); + HashMap accessNeighborhood = graph.accessNeighborhood(node, 0); + int size = accessNeighborhood.size(); + System.out.println(String.format("%s,%s", i, size)); + + } + } + + @Test + public void createGraphTest50k() { + OSMDBImporter importer = new OSMDBImporter("view_exp_50k", PATH_GRAPH); + GraphBounds graph = importer.execute(); + Assert.assertNotNull(graph); + Assert.assertEquals(328, graph.getCategories().size()); // 425 + Assert.assertEquals(33595, graph.getNumberOfNodes()); // 236216 + Assert.assertEquals(42385, graph.getNumberOfEdges()); + + for (int i = 0; i < graph.getNumberOfNodes(); i++) { + Node node = graph.getNode(i); + HashMap accessNeighborhood = graph.accessNeighborhood(node, 0); + int size = accessNeighborhood.size(); + System.out.println(String.format("%s,%s", i, size)); + + } + } + + @Test + public void createGraphTest300k() { + OSMDBImporter importer = new OSMDBImporter("view_exp_300mil", PATH_GRAPH); + GraphBounds graph = importer.execute(); + Assert.assertNotNull(graph); + Assert.assertEquals(425, graph.getCategories().size()); + Assert.assertEquals(236216, graph.getNumberOfNodes()); + Assert.assertEquals(275720, graph.getNumberOfEdges()); + } +} diff --git a/core/src/test/java/org/graphast/importer/PoiTaxiFortalezaImporterTest.java b/core/src/test/java/org/graphast/importer/PoiTaxiFortalezaImporterTest.java new file mode 100644 index 0000000..577964a --- /dev/null +++ b/core/src/test/java/org/graphast/importer/PoiTaxiFortalezaImporterTest.java @@ -0,0 +1,26 @@ +package org.graphast.importer; + +import org.graphast.config.Configuration; +import org.graphast.model.GraphBounds; +import org.junit.Assert; +import org.junit.Test; + +public class PoiTaxiFortalezaImporterTest { + private static final String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + @Test + public void createGraphWithPoiTaxiTest() { + + OSMDBImporter importer = new OSMDBImporter("view_exp_1k", PATH_GRAPH); + GraphBounds graph = importer.execute(); + + PoiTaxiFortalezaImporter importerWithPoi = new PoiTaxiFortalezaImporter(graph); + GraphBounds graphWithPoi = importerWithPoi.getGraph(); + + Assert.assertNotNull(graphWithPoi); + Assert.assertEquals(809, graph.getNumberOfNodes()); + Assert.assertEquals(844, graph.getNumberOfEdges()); + Assert.assertEquals(15, graph.getCategories().size()); + + } +} diff --git a/core/src/test/java/org/graphast/knn/RNNBreadthFirstSearchTest.java b/core/src/test/java/org/graphast/knn/RNNBreadthFirstSearchTest.java new file mode 100644 index 0000000..5ca41f4 --- /dev/null +++ b/core/src/test/java/org/graphast/knn/RNNBreadthFirstSearchTest.java @@ -0,0 +1,330 @@ +package org.graphast.knn; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Date; + +import org.graphast.config.Configuration; +import org.graphast.exception.PathNotFoundException; +import org.graphast.graphgenerator.GraphGenerator; +import org.graphast.graphgenerator.GraphGeneratorGridTester; +import org.graphast.model.GraphBounds; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.rnn.RNNBreadthFirstSearch; +import org.graphast.util.DateUtils; +import org.graphast.util.FileUtils; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; + +public class RNNBreadthFirstSearchTest { + + private static GraphBounds graphBounds; + private static GraphBounds graphBoundsReverse; + + private Integer idCustomer; + private Date maxTravelTime; + private Date hourServiceTime; + private String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + public void setUpNoRandomGraph() throws ParseException, IOException { + + // Tempo para atendiemento + maxTravelTime = DateUtils.parseDate(23, 59, 59); + + // Hora que ele realiza a chamada do serviço meia-noite e vinte minutos + hourServiceTime = DateUtils.parseDate(00, 00, 00); + + graphBounds = new GraphGenerator().generateExampleTAXI(); +// graphBoundsReverse = new GraphGenerator().generateExampleTAXI(); +// graphBoundsReverse.reverseGraph(); + } + + public void setUpRandomGraph(int qtdX, int qtdY, int percentPois) throws ParseException { + + // Tempo para atendiemento + maxTravelTime = DateUtils.parseDate(23, 59, 59); + + // Hora que ele realiza a chamada do serviço meia-noite e vinte minutos + hourServiceTime = DateUtils.parseDate(00, 00, 00); + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, qtdX, qtdY, percentPois); + graphSynthetic.generateGraph(); + + graphBoundsReverse = graphSynthetic.getGraph(); + graphBounds = graphBoundsReverse; + graphBoundsReverse.reverseGraph(); + } + + // TESTE 1: (EXCEPTION) Verificamos se o cliente que chama o táxi está no mesmo ponto + // de um determinado taxita. + @Test + public void taxiSearchExpected_I() throws ParseException, IOException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(4); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + Assert.assertNotNull(nearestNeighbor); + assertEquals("Deve retornar o vid esperado.", 4, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 0, nearestNeighbor.getDistance()/1000/60); + + ArrayList path = new ArrayList<>(); + path.add(4l); + assertEquals("Deve retornar o caminho esperado.", path.get(0), nearestNeighbor.getPath().get(0)); + } + + // TESTE 1.1: (EXCEPTION) Nenhum taxista é encontrado na malha, para a quantidade de tempo + // superior necessario para atendimento (11 minutos e 59 segundos) + @Test(expected = PathNotFoundException.class) + public void taxiSearchExpected_II() throws ParseException, IOException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(8); + + // Tempo para atendiemento + maxTravelTime = DateUtils.parseDate(0, 11, 59); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBounds); + taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + } + + // TESTE 2: O cliente está em um vértice vizinho ao taxista. CLIENTE -> TAXISTA (NÃO REVERSO) + @Test + public void taxiSearchNeighbor() throws IOException, ParseException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(7); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + ArrayList path_result = new ArrayList<>(); + path_result.add(4l); + path_result.add(3l); + path_result.add(2l); + path_result.add(7l); + + assertEquals("Deve retornar o vid esperado.", 4l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 37, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + // TESTE 2.1: O cliente está em um vértice vizinho ao taxista. CLIENTE -> TAXISTA (REVERSO) + @Test + public void taxiSearchNeighborReverso() throws IOException, ParseException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(7); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 12, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + // Tem três taxista na malha, custumer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolution() throws IOException, ParseException { + + //Cliente que realiza a chamada do serviço + Integer idCustomer = Integer.valueOf(5); + + //Tempo para atendiemento - 39 minutos + Date serviceTime = DateUtils.parseDate(0, 39, 0); + + //Hora que ele realiza a chamada do serviço - meia-noite e vinte segundos + Date hourServiceTime = DateUtils.parseDate(00, 00, 00); + + graphBounds = new GraphGenerator().generateExampleTAXI(); + graphBoundsReverse = new GraphGenerator().generateExampleTAXI(); + graphBoundsReverse.reverseGraph(); + + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), serviceTime, hourServiceTime); + + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 39, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + + // TESTE 3: O cliente está em um vértice vizinho a dois taxistas. Mas com + // pesos das aresta para chegar ao cliente diferente. Cliente:8; Taxista 1: 4, 12 minutos; Taxista 1: 9, 15 minutos. + @Test + public void taxiSearchNeighborWithDifferentWeight() throws IOException, ParseException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(8); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + ArrayList path_result = new ArrayList<>(); + path_result.add(4l); + path_result.add(8l); + + assertEquals("Deve retornar o vid esperado.", 4l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 12, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + // TESTE 4: O cliente está em um vértice vizinho a dois taxistas. Mas com + // pesos das arestas para chegar ao cliente iguais + @Test + public void taxiSearchNeighborWithEqualsWeight() throws IOException, ParseException { + + setUpNoRandomGraph(); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(8); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + ArrayList path_result = new ArrayList<>(); + path_result.add(4l); + path_result.add(8l); + + //Retorna o que possui o menor tempo para a travessia, a Queue realiza o compare para a ordenação. + assertEquals("Deve retornar o vid esperado.", 4l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 12, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + // Tem três taxista na malha, customer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolutionTimeForTheCallMidnight() throws IOException, ParseException { + + GraphBounds graphBoundsReverse = new GraphGenerator().generateExampleTaxi15to15minutes(); + graphBoundsReverse.reverseGraph(); + + //Tempo para atendiemento - 40 minutos + maxTravelTime = DateUtils.parseDate(00, 38, 00); + + //Hora que ele realiza a chamada do serviço - meia-noite + hourServiceTime = DateUtils.parseDate(00, 00, 00); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(5); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + System.out.println(nearestNeighbor); + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 28, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + // Tem três taxista na malha, customer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolutionTimeForTheCallHourServiceInit() throws IOException, ParseException { + + GraphBounds graphBoundsReverse = new GraphGenerator().generateExampleTaxi15to15minutes(); + graphBoundsReverse.reverseGraph(); + + //Tempo para atendiemento - 40 minutos + maxTravelTime = DateUtils.parseDate(2, 52, 00); + + //Hora que ele realiza a chamada do serviço - meia-noite e quinze minutos + hourServiceTime = DateUtils.parseDate(00, 15, 00); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(5); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + System.out.println(nearestNeighbor); + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 52, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + } + + @Test + public void taxiBetterWaytRandomGraphOneByOne() throws ParseException { + + setUpRandomGraph(1,1,1); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(0); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + assertEquals("Deve retornar o vid esperado.", 0l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 0, nearestNeighbor.getDistance()/1000/60); + + ArrayList path = new ArrayList<>(); + path.add(0l); + assertEquals("Deve retornar o caminho esperado.", path , nearestNeighbor.getPath()); + } + + @Test + public void taxiBetterWaytRandomGraphTwoByTwo() throws ParseException { + + setUpRandomGraph(2, 2, 1); + + // Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(0); + + RNNBreadthFirstSearch taxiSearch = new RNNBreadthFirstSearch(graphBoundsReverse); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBoundsReverse.getNode(idCustomer), maxTravelTime, hourServiceTime); + + Assert.assertNotNull(nearestNeighbor); + } + + @AfterClass + public static void tearDown() { + + FileUtils.deleteDir(Configuration.USER_HOME + "/graphhopper/test"); + FileUtils.deleteDir(Configuration.USER_HOME + "/graphast/test"); + } +} diff --git a/core/src/test/java/org/graphast/knn/RNNComparatorTest.java b/core/src/test/java/org/graphast/knn/RNNComparatorTest.java new file mode 100644 index 0000000..1533543 --- /dev/null +++ b/core/src/test/java/org/graphast/knn/RNNComparatorTest.java @@ -0,0 +1,191 @@ +package org.graphast.knn; + +import java.io.IOException; +import java.text.ParseException; +import java.util.Date; + +import org.graphast.config.Configuration; +import org.graphast.graphgenerator.GraphGeneratorGridTester; +import org.graphast.model.GraphBounds; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.rnn.RNNBacktrackingSearch; +import org.graphast.query.rnn.RNNBreadthFirstSearch; +import org.graphast.util.DateUtils; +import org.graphast.util.FileUtils; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; + +public class RNNComparatorTest { + + private Integer idCustomer = null; + private Date endServiceTime = null; + private Date startServiceTime = null; + private Double percentagemPoi = null; + private String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + @Before + public void setUp() throws ParseException, IOException { + + //Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(0); + + //Tempo para atendiemento - 23h 59m 59s + endServiceTime = DateUtils.parseDate(0, 20, 00); + + //Hora que ele realiza a chamada do serviço + startServiceTime = DateUtils.parseDate(00, 00, 00); + + percentagemPoi = Double.valueOf(1); + } + + // 1k (1024 pontos) + @Test + public void taxiSearchSytenticGraph1k() throws IOException, ParseException { + + for(int i=0; i<100; i++) { + + int comprimento = 32; + int altura = 32; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + //==== SOLUÇÃO I ==== + long startSolution1 = System.currentTimeMillis(); + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graph); + NearestNeighbor solution1 = taxiSearch.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution1 = System.currentTimeMillis(); + long timeSolution1 = endSolution1-startSolution1; + + graph.reverseGraph(); + + //==== SOLUÇÃO III ==== + long startSolution3 = System.currentTimeMillis(); + RNNBreadthFirstSearch taxiSearchRestritionsOSR = new RNNBreadthFirstSearch(graph); + NearestNeighbor solution3 = taxiSearchRestritionsOSR.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution3 = System.currentTimeMillis(); + long timeSolution3 = endSolution3-startSolution3; + + System.out.println(String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", timeSolution1, timeSolution3, solution1.getId(), solution3.getId(), solution1.getDistance(), + solution3.getDistance(), solution1.getPath().size(), solution3.getPath().size(), solution1.getPath(), solution3.getPath())); + } + } + + // 10k (10000 pontos) + @Test + public void taxiSearchSytenticGraph10k() throws IOException, ParseException { + + for(int i=0; i<100; i++) { + + int comprimento = 100; + int altura = 100; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + //==== SOLUÇÃO I ==== + long startSolution1 = System.currentTimeMillis(); + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graph); + NearestNeighbor solution1 = taxiSearch.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution1 = System.currentTimeMillis(); + long timeSolution1 = endSolution1-startSolution1; + + graph.reverseGraph(); + + //==== SOLUÇÃO III ==== + long startSolution3 = System.currentTimeMillis(); + RNNBreadthFirstSearch taxiSearchRestritionsOSR = new RNNBreadthFirstSearch(graph); + NearestNeighbor solution3 = taxiSearchRestritionsOSR.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution3 = System.currentTimeMillis(); + long timeSolution3 = endSolution3-startSolution3; + + System.out.println(String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", timeSolution1, timeSolution3, solution1.getId(), solution3.getId(), solution1.getDistance(), + solution3.getDistance(), solution1.getPath().size(), solution3.getPath().size(), solution1.getPath(), solution3.getPath())); + } + } + + // 100k (99856 pontos) + @Test + public void taxiSearchSytenticGraph100k() throws IOException, ParseException { + + for(int i=0; i<100; i++) { + + int comprimento = 316; + int altura = 316; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + GraphBounds reverseGraph = graphSynthetic.getGraph(); + graph = reverseGraph; + reverseGraph.reverseGraph(); + + //==== SOLUÇÃO I ==== + long startSolution1 = System.currentTimeMillis(); + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graph); + NearestNeighbor solution1 = taxiSearch.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution1 = System.currentTimeMillis(); + long timeSolution1 = endSolution1-startSolution1; + + + //==== SOLUÇÃO III ==== + long startSolution3 = System.currentTimeMillis(); + RNNBreadthFirstSearch taxiSearchRestritionsOSR = new RNNBreadthFirstSearch(reverseGraph); + NearestNeighbor solution3 = taxiSearchRestritionsOSR.search(reverseGraph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution3 = System.currentTimeMillis(); + long timeSolution3 = endSolution3-startSolution3; + + System.out.println(String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", timeSolution1, timeSolution3, solution1.getId(), solution3.getId(), solution1.getDistance(), + solution3.getDistance(), solution1.getPath().size(), solution3.getPath().size(), solution1.getPath(), solution3.getPath())); + } + } + + // 1G (1000000 pontos) + @Test + public void taxiSearchSytenticGraph1000k() throws IOException, ParseException { + + for(int i=0; i<10; i++) { + + int comprimento = 1000; + int altura = 1000; + + GraphGeneratorGridTester graphSynthetic = new GraphGeneratorGridTester(PATH_GRAPH, comprimento,altura, percentagemPoi); + graphSynthetic.generateGraph(); + GraphBounds graph = graphSynthetic.getGraph(); + + GraphBounds reverseGraph = graphSynthetic.getGraph(); + graph = reverseGraph; + reverseGraph.reverseGraph(); + + //==== SOLUÇÃO I ==== + long startSolution1 = System.currentTimeMillis(); + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graph); + NearestNeighbor solution1 = taxiSearch.search(graph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution1 = System.currentTimeMillis(); + long timeSolution1 = endSolution1-startSolution1; + + + //==== SOLUÇÃO III ==== + long startSolution3 = System.currentTimeMillis(); + RNNBreadthFirstSearch taxiSearchRestritionsOSR = new RNNBreadthFirstSearch(reverseGraph); + NearestNeighbor solution3 = taxiSearchRestritionsOSR.search(reverseGraph.getNode(idCustomer), endServiceTime, startServiceTime); + long endSolution3 = System.currentTimeMillis(); + long timeSolution3 = endSolution3-startSolution3; + + System.out.println(String.format("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s", timeSolution1, timeSolution3, solution1.getId(), solution3.getId(), solution1.getDistance(), + solution3.getDistance(), solution1.getPath().size(), solution3.getPath().size(), solution1.getPath(), solution3.getPath())); + } + } + + + @AfterClass + public static void tearDown() { + + FileUtils.deleteDir(Configuration.USER_HOME + "/graphhopper/test"); + FileUtils.deleteDir(Configuration.USER_HOME + "/graphast/test"); + } +} diff --git a/core/src/test/java/org/graphast/knn/RNNDepthFirstSearchTest.java b/core/src/test/java/org/graphast/knn/RNNDepthFirstSearchTest.java new file mode 100644 index 0000000..9a8e253 --- /dev/null +++ b/core/src/test/java/org/graphast/knn/RNNDepthFirstSearchTest.java @@ -0,0 +1,265 @@ +package org.graphast.knn; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.graphast.config.Configuration; +import org.graphast.exception.PathNotFoundException; +import org.graphast.graphgenerator.GraphGenerator; +import org.graphast.importer.OSMDBImporter; +import org.graphast.model.Edge; +import org.graphast.model.GraphBounds; +import org.graphast.query.knn.NearestNeighbor; +import org.graphast.query.rnn.RNNBacktrackingSearch; +import org.graphast.query.route.shortestpath.dijkstra.Dijkstra; +import org.graphast.query.route.shortestpath.dijkstra.DijkstraLinearFunction; +import org.graphast.query.route.shortestpath.model.Path; +import org.graphast.util.DateUtils; +import org.graphast.util.FileUtils; +import org.graphast.util.NumberUtils; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +public class RNNDepthFirstSearchTest { + private static final String PATH_GRAPH = Configuration.USER_HOME + "/graphast/test/example"; + + private Integer idCustomer; + private Date maxTravelTime; + private Date hourServiceTime; + + @Before + public void setUp() throws ParseException, IOException { + + //Cliente que realiza a chamada do serviço + idCustomer = Integer.valueOf(5); + + //Hora que ele realiza a chamada do serviço - meia-noite e vinte segundo + hourServiceTime = DateUtils.parseDate(00, 00, 00); + } + + @Test + public void reverteGraphTest() throws IOException { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTAXI(); + GraphBounds graphBoundsReverse = new GraphGenerator().generateExampleTAXI(); + graphBoundsReverse.reverseGraph(); + + //checar quantidade de vértices que foram invertidos + assertEquals("A quantidade de Vértices esperado não corresponde com a quantidade retornada.", + 10, graphBounds.getNumberOfNodes()); + + //checar quantidade de edge que foram invertidos + assertEquals("A quantidade de Edges esperados não corresponde com a quantidade retornada.", + 13, graphBounds.getNumberOfEdges()); + + List latitudesTo = new ArrayList(); + List longitudeTo = new ArrayList(); + List idTo = new ArrayList(); + + for (int i = 0; i < graphBounds.getNumberOfEdges(); i++) { + Edge edge = graphBounds.getEdge(i); + double latitude = graphBounds.getNode(edge.getToNode()).getLatitude(); + double longitude = graphBounds.getNode(edge.getToNode()).getLongitude(); + double id = graphBounds.getNode(edge.getToNode()).getId(); + + latitudesTo.add(latitude); + longitudeTo.add(longitude); + idTo.add(id); + } + + //Reverse Graph + graphBounds.reverseGraph(); + + List latitudesFromReverse = new ArrayList(); + List longitudeFromReverse = new ArrayList(); + List idFromReverse = new ArrayList(); + + for (int i = 0; i < graphBounds.getNumberOfEdges(); i++) { + Edge edge = graphBounds.getEdge(i); + double latitude = graphBounds.getNode(edge.getFromNode()).getLatitude(); + double longitude = graphBounds.getNode(edge.getFromNode()).getLongitude(); + double id = graphBounds.getNode(edge.getFromNode()).getId(); + + latitudesFromReverse.add(latitude); + longitudeFromReverse.add(longitude); + idFromReverse.add(id); + } + + //checar quantidade de vértices que foram invertidos + assertEquals("A quantidade de Vértices esperado não corresponde com a quantidade retornada após o reverso do grafo.", + 10, graphBounds.getNumberOfNodes()); + + //checar quantidade de edge que foram invertidos + assertEquals("A quantidade de Edges esperados não corresponde com a quantidade retornada após o reverso do grafo.", + 13, graphBounds.getNumberOfEdges()); + + assertEquals(latitudesTo, latitudesFromReverse); + assertEquals(longitudeTo, longitudeFromReverse); + assertEquals(idTo, idFromReverse); + + } + + // Tem três taxista na malha, customer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolution() { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTAXI(); + + //Tempo para atendiemento - 39 minutos + maxTravelTime = DateUtils.parseDate(0, 39, 00); + + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + System.out.println(nearestNeighbor); + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 39, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + Assert.assertNotNull(nearestNeighbor.getNumberVisitedNodes()); + } + + // Tem três taxista na malha, custumer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + public void returnNullSolution() throws PathNotFoundException { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTAXI(); + + //Tempo para atendiemento - 38 minutos + maxTravelTime = DateUtils.parseDate(0, 38, 00); + + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + Assert.assertNull(nearestNeighbor); + } + + // Tem três taxista na malha, customer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolutionTimeForTheCallMidnight() throws PathNotFoundException { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTaxi15to15minutes(); + + //Tempo para atendiemento - 40 minutos + maxTravelTime = DateUtils.parseDate(0, 40, 00); + + //Hora que ele realiza a chamada do serviço - meia-noite + hourServiceTime = DateUtils.parseDate(00, 00, 00); + + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + System.out.println(nearestNeighbor); + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 40, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + Assert.assertNotNull(nearestNeighbor.getNumberVisitedNodes()); + } + + // Tem três taxista na malha, customer = 5, cab 1 = 1, cab 2 = 4 e cab 3 = 9 + @Test + public void returnBetterSolutionTimeForTheCallHourServiceInit() throws PathNotFoundException { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTaxi15to15minutes(); + + //Tempo para atendiemento - 39 minutos + maxTravelTime = DateUtils.parseDate(0, 40, 00); + + //Hora que ele realiza a chamada do serviço - meia-noite e vinte segundo + hourServiceTime = DateUtils.parseDate(00, 15, 00); + + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graphBounds); + NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + + System.out.println(nearestNeighbor); + Assert.assertNotNull(nearestNeighbor); + + ArrayList path_result = new ArrayList<>(); + path_result.add(1l); + path_result.add(7l); + path_result.add(6l); + path_result.add(5l); + + assertEquals("Deve retornar o vid esperado.", 1l, nearestNeighbor.getId()); + assertEquals("Deve retornar o custo esperado.", 29, nearestNeighbor.getDistance()/1000/60); + assertEquals("Deve retornar o caminho esperado.", path_result , nearestNeighbor.getPath()); + Assert.assertNotNull(nearestNeighbor.getNumberVisitedNodes()); + } + + @Test + public void baseTest() throws IOException, ParseException { + + GraphBounds graphBounds = new GraphGenerator().generateExampleTAXI(); + + Dijkstra dijkstraShortestPathLinearFunction = new DijkstraLinearFunction(graphBounds); + Path shortestPath = dijkstraShortestPathLinearFunction.shortestPath(1l, 5l); + Assert.assertEquals(39, shortestPath.getTotalCost()/1000/60, 0); + + } + + @Ignore + @Test + public void dbTest() { + + OSMDBImporter importer = new OSMDBImporter("view_exp_1k", PATH_GRAPH); + GraphBounds graphBounds = importer.execute(); + + RNNBacktrackingSearch taxiSearch = new RNNBacktrackingSearch(graphBounds); +// NearestNeighbor nearestNeighbor = taxiSearch.search(graphBounds.getNode(idCustomer), maxTravelTime, hourServiceTime); + //Tempo para atendiemento - 39 minutos + maxTravelTime = DateUtils.parseDate(00, 59, 00); + //Hora que ele realiza a chamada do serviço - meia-noite e vinte segundo + hourServiceTime = DateUtils.parseDate(00, 00, 00); + + for (int i = 0; i < 100; i++) { + + long numberOfNodes = graphBounds.getNumberOfNodes(); + long customer = Double.valueOf(NumberUtils.generatePdseurandom(0, Long.valueOf(numberOfNodes).intValue())).longValue(); + NearestNeighbor solution2 = taxiSearch.search(graphBounds.getNode(customer), maxTravelTime, hourServiceTime); + + Long idSolution2 = null; + Integer distance2 = null; + Integer size2 = null; + ArrayList path2 = null; + Long externalId2 = null; + if(solution2 != null) { + idSolution2 = solution2.getId(); + distance2 = solution2.getDistance(); + size2 = solution2.getPath().size(); + path2 = solution2.getPath(); + externalId2 = graphBounds.getNode(solution2.getId()).getExternalId(); + + } + + String.format("%s;%s;%s;%s;%s", idSolution2, externalId2, distance2, size2, path2); + } + } + + @AfterClass + public static void tearDown() { + + FileUtils.deleteDir(Configuration.USER_HOME + "/graphhopper/test"); + FileUtils.deleteDir(Configuration.USER_HOME + "/graphast/test"); + } +} diff --git a/core/src/test/java/org/graphast/piecewise/GeneratorFunctionPiecewiseDatabaseTest.java b/core/src/test/java/org/graphast/piecewise/GeneratorFunctionPiecewiseDatabaseTest.java new file mode 100644 index 0000000..7d5c6ff --- /dev/null +++ b/core/src/test/java/org/graphast/piecewise/GeneratorFunctionPiecewiseDatabaseTest.java @@ -0,0 +1,83 @@ +package org.graphast.piecewise; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; + +import org.graphast.util.ConnectionJDBC; +import org.junit.Assert; +import org.junit.Test; + +import com.github.rcaller.rStuff.RCaller; +import com.github.rcaller.rStuff.RCode; + +public class GeneratorFunctionPiecewiseDatabaseTest { + + private static final String RSCRIPT = "/usr/bin/Rscript"; + + @Test + public void getConnectionTest() throws ClassNotFoundException, SQLException, IOException { + + Connection connection = ConnectionJDBC.getConnection(); + Assert.assertNotNull(connection); + } + + @Test + public void getDataTest() throws PiecewiseException { + + IBuilderDatasource generatorFunctionPiecewise = new BuilderDatasourceDB(); + double[][] data = generatorFunctionPiecewise.getData(); + int length = data.length; + + Assert.assertEquals(28, length); + } + + @Test + public void verifyPointsTest() throws IOException, PiecewiseException { + + RCaller caller = new RCaller(); + RCode code = caller.getRCode(); + caller.setRscriptExecutable(RSCRIPT); + + IBuilderDatasource generatorFunctionPiecewise = new BuilderDatasourceDB(); + double[][] data = generatorFunctionPiecewise.getData(); + + code.addDoubleMatrix("matrix", data); + code.addRCode("dados.frame <- data.frame(matrix)"); + code.addRCode("dados.loess <- loess(dados.frame)"); + code.addRCode("xl <- with(dados.loess, seq(min(x), max(x), (max(x) - min(x))/1000))"); + code.addRCode("y.predict <- predict(dados.loess, xl)"); + code.addRCode("infl <- c(FALSE, diff(diff(y.predict)>0)!=0)"); + code.addRCode("pontoInicial <- cbind(xl, y.predict)[xl == min(xl),]"); + code.addRCode("pontosInflexao <- cbind(xl, y.predict)[infl,]"); + code.addRCode("pontoFinal <- cbind(xl, y.predict)[xl == max(xl),]"); + code.addRCode("allObjects <- list(pontoInicial=pontoInicial, pontoFinal=pontoFinal, pontosInflexao=pontosInflexao)"); + + caller.setRCode(code); + caller.runAndReturnResult("allObjects"); + + Assert.assertNotNull(caller.getParser().getXMLFileAsString()); + System.out.println(caller.getParser().getXMLFileAsString().toString()); + + double[] pontoInicial = caller.getParser().getAsDoubleArray("pontoInicial"); + Assert.assertEquals(Double.valueOf("1201977368000"), Double.valueOf(pontoInicial[0])); + Assert.assertEquals(Double.valueOf("295522763826171"), Double.valueOf(pontoInicial[1])); + + double[] pontosInflexao = caller.getParser().getAsDoubleArray("pontosInflexao"); + int length = pontosInflexao.length; + Assert.assertEquals(6, length); + + Assert.assertEquals(Double.valueOf("1202063763696"), Double.valueOf(pontosInflexao[0])); + Assert.assertEquals(Double.valueOf("55328186.6718641"), Double.valueOf(pontosInflexao[length/2])); + } + + @Test + public void generationFunctionEdgeTest() throws NumberFormatException, PiecewiseException { + + GeneratorFunctionLoess generatorFunctionPiecewise = new GeneratorFunctionLoess(); + Function value = generatorFunctionPiecewise.gerFuntionEdge(1l, Long.valueOf("1201977368000").longValue()); + + System.out.println(value); + Assert.assertNotNull(value); + } +} \ No newline at end of file diff --git a/core/src/test/java/org/graphast/piecewise/GeneratorFunctionRefactore.java b/core/src/test/java/org/graphast/piecewise/GeneratorFunctionRefactore.java new file mode 100644 index 0000000..53861d3 --- /dev/null +++ b/core/src/test/java/org/graphast/piecewise/GeneratorFunctionRefactore.java @@ -0,0 +1,80 @@ +package org.graphast.piecewise; + +import java.util.Calendar; + +import org.graphast.graphgenerator.GraphGenerator; +import org.graphast.model.Graph; +import org.junit.Test; + +public class GeneratorFunctionRefactore { + + // Com um graph já existente, basta setar a função. + // Loess sendo implementado em R + @Test + public void definedFuntionLoessREdgeTest() throws PiecewiseException { + + //Hora do dia: Dia: 16/01/2016 Hora: 11:30:00 + Calendar calendar = Calendar.getInstance(); + calendar.set(2016, 01, 16, 11, 30, 00); + long timestamp = calendar.getTimeInMillis(); + + GraphGenerator graphGenerator = new GraphGenerator(); + Graph graph = graphGenerator.generateExample(); + + IBuilderDatasource generatorFunctionPiecewise = new BuilderDatasourceDB(); + double[][] coleta = generatorFunctionPiecewise.getData(); + IManipulatorEngine engineR = new ManipulatorR(coleta); + + IGeneratorFunction generatorFunction = new GeneratorFunctionLoess(engineR); + Function function = generatorFunction.gerFuntionEdge(1l, timestamp); + + graph.setFuntionEdge(1l, function); + } + + // Com um graph já existente, basta setar a função. + // Loess sendo implementado em Java + @Test + public void definedFuntionLoessJavaEdgeTest() { + + //Hora do dia: Dia: 16/01/2016 Hora: 11:30:00 + Calendar calendar = Calendar.getInstance(); + calendar.set(2016, 01, 16, 11, 30, 00); + long timestamp = calendar.getTimeInMillis(); + + GraphGenerator graphGenerator = new GraphGenerator(); + Graph graph = graphGenerator.generateExample(); + + IManipulatorEngine engineR = new ManipulatorJava(); + IGeneratorFunction generatorFunction = new GeneratorFunctionLoess(engineR); + Function function = generatorFunction.gerFuntionEdge(1l, timestamp); + + graph.setFuntionEdge(1l, function); + } + + // Com um graph já existente, basta setar a função. + @Test + public void definedFuntionMatrixEdgeTest() throws PiecewiseException { + + //Hora do dia: Dia: 16/01/2016 Hora: 11:30:00 + Calendar calendar = Calendar.getInstance(); + calendar.set(2016, 01, 16, 11, 30, 00); + long timestamp = calendar.getTimeInMillis(); + + GraphGenerator graphGenerator = new GraphGenerator(); + Graph graph = graphGenerator.generateExample(); + + IBuilderDatasource generatorFunctionPiecewise = new BuilderDatasourceDB(); + double[][] coleta = generatorFunctionPiecewise.getData(); + IManipulatorEngine engineR = new ManipulatorR(coleta); + + IGeneratorFunction generatorFunction = new GeneratorFunctionMatrix(engineR); + Function function = generatorFunction.gerFuntionEdge(1l, timestamp); + + graph.setFuntionEdge(1l, function); + } + + //Criar o graph com as funções dos edges + @Test + public void createGraphWithFuntionEdgeTest() { + } +} \ No newline at end of file diff --git a/core/src/test/java/org/graphast/piecewise/GeneratorGraphFunctionPiecewiseTest.java b/core/src/test/java/org/graphast/piecewise/GeneratorGraphFunctionPiecewiseTest.java new file mode 100644 index 0000000..1f51f88 --- /dev/null +++ b/core/src/test/java/org/graphast/piecewise/GeneratorGraphFunctionPiecewiseTest.java @@ -0,0 +1,24 @@ +package org.graphast.piecewise; + +import org.graphast.config.Configuration; +import org.graphast.model.Graph; +import org.graphast.model.GraphImpl; +import org.graphast.model.NodeImpl; +import org.junit.Test; + +public class GeneratorGraphFunctionPiecewiseTest { + + + @Test + public void createGraphTest() throws PiecewiseException { + + Graph graph = new GraphImpl(Configuration.USER_HOME + "/graphast/test/examplepiecewise"); + + NodeImpl node1 = new NodeImpl(1l, 10d, 10d, "label node 1"); + graph.addNode(node1); + + NodeImpl node2 = new NodeImpl(1l, 10d, 10d, "label node 1"); + graph.addNode(node2); + } +} + diff --git a/core/src/test/java/org/graphast/piecewise/RCallerEnvironmentsTest.java b/core/src/test/java/org/graphast/piecewise/RCallerEnvironmentsTest.java new file mode 100644 index 0000000..c60791b --- /dev/null +++ b/core/src/test/java/org/graphast/piecewise/RCallerEnvironmentsTest.java @@ -0,0 +1,114 @@ +package org.graphast.piecewise; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +import com.github.rcaller.rStuff.RCaller; +import com.github.rcaller.rStuff.RCode; + +public class RCallerEnvironmentsTest { + + private static final String RSCRIPT = "C:\\Program Files\\R\\R-3.2.2\\bin\\Rscript.exe"; + + @Test + public void createRscriptTest() { + + RCaller rcaller = new RCaller(); + rcaller.setRscriptExecutable(RSCRIPT); + Assert.assertNotNull(rcaller.getRCode()); + } + + @Test + public void baseLinearOutXMLTest() throws IOException { + + RCaller caller = new RCaller(); + caller.setRscriptExecutable(RSCRIPT); + RCode code = caller.getRCode(); + + code.addRCode("set.seed(123)"); + code.addRCode("x<-rnorm(10)"); + code.addRCode("y<-rnorm(10)"); + code.addRCode("ols<-lm(y~x)"); + + caller.setRCode(code); + caller.runAndReturnResult("ols"); + + System.out.println(caller.getParser().getXMLFileAsString()); + Assert.assertNotNull(caller.getParser().getXMLFileAsString()); + } + + + @Test + public void loessTest() throws IOException { + + RCaller caller = new RCaller(); + RCode code = caller.getRCode(); + caller.setRscriptExecutable(RSCRIPT); + + code.addRCode("set.seed(123)"); + code.addRCode("x<-rnorm(10)"); + code.addRCode("y<-rnorm(10)"); + code.addRCode("dados.loess <- loess(y ~ x)"); + + caller.setRCode(code); + caller.runAndReturnResult("dados.loess"); + + System.out.println(caller.getParser().getXMLFileAsString()); + Assert.assertNotNull(caller.getParser().getXMLFileAsString()); + } + + @Test + public void loessWithRandomDataTest() throws IOException { + + RCaller caller = new RCaller(); + RCode code = caller.getRCode(); + + caller.setRscriptExecutable(RSCRIPT); + + code.addRCode("set.seed(123)"); + code.addRCode("x<-rnorm(10)"); + code.addRCode("y<-rnorm(10)"); + code.addRCode("dados.loess <- loess(y ~ x)"); + code.addRCode("xl <- seq(min(x), max(x), (max(x) - min(x))/1000)"); + code.addRCode("y.predict <- predict(dados.loess, xl)"); + code.addRCode("infl <- c(FALSE, diff(diff(y.predict)>0)!=0)"); + code.addRCode("objMin <- cbind(xl, y.predict)[xl == min(xl),]"); + code.addRCode("obj <- cbind(xl, y.predict)[infl,]"); + code.addRCode("objMax <- cbind(xl, y.predict)[xl == max(xl),]"); + code.addRCode("allObjects<-list(resultMin=objMin, resultMax=objMax, resultObj=obj)"); + + caller.setRCode(code); + caller.runAndReturnResult("allObjects"); + + System.out.println(caller.getParser().getXMLFileAsString()); + Assert.assertNotNull(caller.getParser().getXMLFileAsString()); + } + + @Test + public void loessWithSynteticDataTest() throws IOException { + + RCaller caller = new RCaller(); + RCode code = caller.getRCode(); + caller.setRscriptExecutable(RSCRIPT); + + code.addRCode("set.seed(123)"); + code.addRCode("x<-rnorm(10)"); + code.addRCode("y<-rnorm(10)"); + code.addRCode("dados.loess <- loess(y ~ x)"); + code.addRCode("xl <- seq(min(x), max(x), (max(x) - min(x))/1000)"); + code.addRCode("y.predict <- predict(dados.loess, xl)"); + code.addRCode("infl <- c(FALSE, diff(diff(y.predict)>0)!=0)"); + code.addRCode("objMin <- cbind(xl, y.predict)[xl == min(xl),]"); + code.addRCode("obj <- cbind(xl, y.predict)[infl,]"); + code.addRCode("objMax <- cbind(xl, y.predict)[xl == max(xl),]"); + code.addRCode("allObjects<-list(resultMin=objMin, resultMax=objMax, resultObj=obj)"); + + caller.setRCode(code); + caller.runAndReturnResult("allObjects"); + + System.out.println(caller.getParser().getXMLFileAsString()); + Assert.assertNotNull(caller.getParser().getXMLFileAsString()); + } +}