/// <summary> /// Creates a new router database. /// </summary> private RouterDb(Guid guid, RoutingNetwork network, AttributesIndex profiles, AttributesIndex meta, IAttributeCollection dbMeta, string[] supportedProfiles) { _guid = guid; _network = network; _edgeProfiles = profiles; _meta = meta; _dbMeta = dbMeta; _supportedProfiles = new HashSet <string>(); foreach (var supportedProfile in supportedProfiles) { _supportedProfiles.Add(supportedProfile); } _contracted = new Dictionary <string, ContractedDb>(); _restrictionDbs = new Dictionary <string, RestrictionsDb>(); _shortcutsDbs = new Dictionary <string, ShortcutsDb>(); }
/// <summary> /// Creates a new router database. /// </summary> public RouterDb(MemoryMap map, float maxEdgeDistance = Constants.DefaultMaxEdgeDistance) { _network = new RoutingNetwork(map, RoutingNetworkProfile.NoCache, maxEdgeDistance); _edgeProfiles = new AttributesIndex(AttributesIndexMode.IncreaseOne | AttributesIndexMode.ReverseAll); _meta = new AttributesIndex(map, AttributesIndexMode.ReverseStringIndexKeysOnly); _metaVertex = new MappedAttributesIndex(); _vertexData = new MetaCollectionDb(); _dbMeta = new AttributeCollection(); _supportedVehicles = new Dictionary <string, Vehicle>(); _supportedProfiles = new Dictionary <string, Profile>(); _contracted = new Dictionary <string, ContractedDb>(); _restrictionDbs = new Dictionary <string, RestrictionsDb>(); _shortcutsDbs = new Dictionary <string, ShortcutsDb>(); _guid = Guid.NewGuid(); }
public void LoadTransportationNetwork(ref RoutingNetwork Network) { timeZone = GetTimeZoneFromAgencyTable(); ///* Add agency table */ //CreateAgencyTable(Network); if (timeZone != null) { CreateStops(Network.MinPoint, Network.MaxPoint, ref Network); GetTimetableData(ref Network, Network.MinPoint, Network.MaxPoint); } else { log.Error("Time zone error, check the agency file"); Environment.Exit(-1); } }
/// <summary> /// Calculates the angle in degress at the given routerpoint over a given distance. /// </summary> /// <param name="point">The router point.</param> /// <param name="network">The routing network.</param> /// <param name="distance">The distance to average over.</param> /// <returns>The angle relative to the meridians.</returns> public static float?Angle(this RouterPoint point, RoutingNetwork network, float distance = 100) { var edge = network.GetEdge(point.EdgeId); var edgeLength = edge.Data.Distance; var distanceOffset = (distance / edgeLength) * ushort.MaxValue; ushort offset1 = 0; ushort offset2 = ushort.MaxValue; if (distanceOffset <= ushort.MaxValue) { // not the entire edge. offset1 = (ushort)System.Math.Max(0, point.Offset - distanceOffset); offset2 = (ushort)System.Math.Min(ushort.MaxValue, point.Offset + distanceOffset); if (offset2 - offset1 == 0) { if (offset1 > 0) { offset1--; } if (offset2 < ushort.MaxValue) { offset2++; } } } // calculate the locations. var location1 = network.LocationOnNetwork(point.EdgeId, offset1); var location2 = network.LocationOnNetwork(point.EdgeId, offset2); if (Coordinate.DistanceEstimateInMeter(location1, location2) < .1) { // distance too small, edge to short. return(null); } // calculate and return angle. var toNorth = new Coordinate(location1.Latitude + 0.001f, location1.Longitude); var angleRadians = DirectionCalculator.Angle(location2, location1, toNorth); return((float)angleRadians.ToDegrees().NormalizeDegrees()); }
/// <summary> /// Creates a new router database. /// </summary> public RouterDb(RoutingNetwork network, AttributesIndex profiles, AttributesIndex meta, IAttributeCollection dbMeta, params Profiles.Profile[] supportedProfiles) { _network = network; _edgeProfiles = profiles; _meta = meta; _dbMeta = dbMeta; _supportedProfiles = new HashSet <string>(); foreach (var supportedProfile in supportedProfiles) { _supportedProfiles.Add(supportedProfile.Name); } _contracted = new Dictionary <string, ContractedDb>(); _restrictionDbs = new Dictionary <string, RestrictionsDb>(); _shortcutsDbs = new Dictionary <string, ShortcutsDb>(); _guid = Guid.NewGuid(); }
/// <summary> /// Gets features for all the given vertices. /// </summary> public static FeatureCollection GetFeaturesFor(this RoutingNetwork network, List <uint> vertices) { var features = new FeatureCollection(); foreach (var vertex in vertices) { float latitude1, longitude1; if (network.GeometricGraph.GetVertex(vertex, out latitude1, out longitude1)) { var vertexLocation = new LocalGeo.Coordinate(latitude1, longitude1); var attributes = new AttributesTable(); attributes.AddAttribute("id", vertex.ToInvariantString()); features.Add(new Feature(new Point(vertexLocation.ToCoordinate()), attributes)); } } return(features); }
public void LoadOSMMap(string path, ref RoutingNetwork Network) { this.Network = Network; XmlReader Reader = XmlReader.Create(path); while (Reader.Read()) { if (Reader.NodeType == XmlNodeType.Element) { switch (Reader.Name) { case "bounds": Network.SetBoundaries( new Point(double.Parse(Reader.GetAttribute("minlat")), double.Parse(Reader.GetAttribute("minlon"))), new Point(double.Parse(Reader.GetAttribute("maxlat")), double.Parse(Reader.GetAttribute("maxlon"))) ); break; case "node": Point P = new Point(double.Parse(Reader.GetAttribute("lat")), double.Parse(Reader.GetAttribute("lon"))); OSMNodeElements.Add(long.Parse(Reader.GetAttribute("id")), P); break; case "way": XElement Way = XElement.Load(Reader.ReadSubtree()); // If is a highway if (Way.Elements("tag").Where(t => t.Attribute("k").Value.ToString() == "highway").Count() != 0) { ProcessWay(Way); } break; default: break; } } else { } } OSMNodeElements.Clear(); }
/// <summary> /// Creates a router point for the given vertex. /// </summary> public static RouterPoint CreateRouterPointForVertex(this RoutingNetwork graph, uint vertex) { float latitude, longitude; if (!graph.GetVertex(vertex, out latitude, out longitude)) { throw new ArgumentException("Vertex doesn't exist, cannot create routerpoint."); } var edges = graph.GetEdgeEnumerator(vertex); while (edges.MoveNext()) { if (edges.DataInverted) { return(new RouterPoint(latitude, longitude, edges.Id, ushort.MaxValue)); } return(new RouterPoint(latitude, longitude, edges.Id, 0)); } throw new ArgumentException("No edges associated with vertex can be used for all of the given profiles, cannot create routerpoint."); }
public void TestWithNoSplits() { var network = new RoutingNetwork(); network.AddVertex(0, 51.268064181900094f, 4.800832271575927f); network.AddVertex(1, 51.2676479869138f, 4.801325798034667f); network.AddEdge(0, 1, new Itinero.Data.Network.Edges.EdgeData() { Distance = 57.69f, Profile = 1, MetaId = 10 }); var splitter = new Itinero.Algorithms.Networks.Preprocessing.MaxDistanceSplitter(network, (x, y) => {}); splitter.Run(); Assert.AreEqual(2, network.VertexCount); Assert.AreEqual(1, network.EdgeCount); }
public void TestThreeEdges() { var graph = new RoutingNetwork(new Itinero.Graphs.Geometric.GeometricGraph(1, 2)); graph.AddVertex(0, 0, 0); graph.AddVertex(1, 1, 1); graph.AddVertex(2, 2, 2); graph.AddEdge(0, 1, new EdgeData() { Profile = 2 }, null); graph.AddEdge(0, 2, new EdgeData() { Profile = 1 }, null); graph.AddEdge(2, 1, new EdgeData() { Profile = 1 }, null); // execute algorithm. var algorithm = new NetworkOptimizer(graph, MergeDelegate); algorithm.Run(); // check result. var edges = graph.GetEdgeEnumerator(0); Assert.AreEqual(2, edges.Count()); Assert.AreEqual(2, edges.First(x => x.To == 1).Data.Profile); Assert.AreEqual(1, edges.First(x => x.To == 2).Data.Profile); edges = graph.GetEdgeEnumerator(1); Assert.AreEqual(2, edges.Count()); Assert.AreEqual(2, edges.First(x => x.To == 0).Data.Profile); Assert.AreEqual(1, edges.First(x => x.To == 2).Data.Profile); edges = graph.GetEdgeEnumerator(2); Assert.AreEqual(2, edges.Count()); Assert.AreEqual(1, edges.First(x => x.To == 0).Data.Profile); Assert.AreEqual(1, edges.First(x => x.To == 1).Data.Profile); }
private void CreateStops(Point MinPoint, Point MaxPoint, ref RoutingNetwork Network) { Stops = new SortedDictionary <string, TNode>(); if (DBConnection.OpenConnection()) { SqlCommand cmd = new SqlCommand(); SqlDataReader reader; // cmd.Connection = DBConnection.Connection; cmd.CommandText = "SELECT * " + "FROM stops " + "WHERE stop_lat >= " + MinPoint.Latitude.ToString() + " AND " + "stop_lon >= " + MinPoint.Longitude.ToString() + " AND " + "stop_lat <= " + MaxPoint.Latitude.ToString() + " AND " + "stop_lon <= " + MaxPoint.Longitude.ToString(); cmd.CommandType = System.Data.CommandType.Text; reader = cmd.ExecuteReader(); // TNode Stop = null; long nextStopId = 1; while (reader.Read()) { Stop = Network.AddNode(nextStopId, new Point( double.Parse(reader["stop_lat"].ToString()), double.Parse(reader["stop_lon"].ToString()) ), reader["stop_id"].ToString(), reader["stop_name"].ToString()); // Stop.StopCode = reader["stop_code"].ToString(); // Stops.Add(Stop.StopId, Stop); ++nextStopId; } reader.Close(); } }
/// <summary> /// Gets all features inside the given bounding box. /// </summary> /// <returns></returns> public static FeatureCollection GetFeaturesIn(this RoutingNetwork network, float minLatitude, float minLongitude, float maxLatitude, float maxLongitude) { var features = new FeatureCollection(); var vertices = Itinero.Algorithms.Search.Hilbert.HilbertExtensions.Search(network.GeometricGraph, minLatitude, minLongitude, maxLatitude, maxLongitude); var edges = new HashSet <long>(); var edgeEnumerator = network.GetEdgeEnumerator(); foreach (var vertex in vertices) { var attributes = new AttributesTable(); attributes.AddAttribute("id", vertex.ToInvariantString()); var vertexLocation = network.GetVertex(vertex); features.Add(new Feature(new Point(vertexLocation.ToCoordinate()), attributes)); edgeEnumerator.MoveTo(vertex); edgeEnumerator.Reset(); while (edgeEnumerator.MoveNext()) { if (edges.Contains(edgeEnumerator.Id)) { continue; } edges.Add(edgeEnumerator.Id); var geometry = new LineString(network.GetShape(edgeEnumerator.Current).ToCoordinatesArray()); attributes = new AttributesTable(); attributes.AddAttribute("id", edgeEnumerator.Id.ToInvariantString()); features.Add(new Feature(geometry, attributes)); } } return(features); }
/// <summary> /// Creates a new router database. /// </summary> private RouterDb(Guid guid, RoutingNetwork network, AttributesIndex profiles, AttributesIndex meta, IAttributeCollection dbMeta, Profiles.Vehicle[] supportedVehicles) { _guid = guid; _network = network; _edgeProfiles = profiles; _meta = meta; _dbMeta = dbMeta; _supportedVehicles = new Dictionary <string, Vehicle>(); _supportedProfiles = new Dictionary <string, Profile>(); foreach (var vehicle in supportedVehicles) { _supportedVehicles[vehicle.Name.ToLowerInvariant()] = vehicle; foreach (var profile in vehicle.GetProfiles()) { _supportedProfiles[profile.FullName.ToLowerInvariant()] = profile; } } _contracted = new Dictionary <string, ContractedDb>(); _restrictionDbs = new Dictionary <string, RestrictionsDb>(); _shortcutsDbs = new Dictionary <string, ShortcutsDb>(); }
public void TestTwoIdenticalEdges() { // create graph with one vertex and start adding 2. var graph = new RoutingNetwork(new Itinero.Graphs.Geometric.GeometricGraph(1, 2)); // make sure to add 1 and 2. graph.AddVertex(0, 0, 0); graph.AddVertex(1, 1, 1); graph.AddVertex(2, 2, 2); graph.AddEdge(0, 1, new EdgeData() { Profile = 1, MetaId = 1, Distance = 10 }, null); graph.AddEdge(1, 2, new EdgeData() { Profile = 1, MetaId = 1, Distance = 20 }, null); // execute algorithm. var algorithm = new NetworkOptimizer(graph, MergeDelegate); algorithm.Run(); // check result. var edges = graph.GetEdgeEnumerator(0); Assert.AreEqual(1, edges.Count()); Assert.AreEqual(1, edges.First().Data.Profile); Assert.AreEqual(1, edges.First().Data.MetaId); Assert.AreEqual(30, edges.First().Data.Distance); var shape = edges.Shape; Assert.IsNotNull(shape); Assert.AreEqual(1, shape.Count); Assert.AreEqual(1, shape.First().Latitude); Assert.AreEqual(1, shape.First().Longitude); }
private static int DynamicDataIntervalTimeRequest = 60000; //ms public HTTPAsyncServer(string url) { DynamicDataIntervalTimeRequest = int.Parse(ConfigurationManager.AppSettings["DynamicDataIntervalTimeRequest"]); m_Timer = new System.Threading.Timer(Timer_Tick_DynamicDataUpdate, null, DynamicDataIntervalTimeRequest, 0); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.FileInfo fileInfo = new System.IO.FileInfo(assembly.Location); lastModified = fileInfo.LastWriteTime; fullPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); productionRoutingNetwork = Program.routingNetwork1; //processRoutingNetwork = Program.routingNetwork2; //HttpListener listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); while (true) { try { /* This will be triggered if a network modification occurs */ HttpListenerContext context = listener.GetContext(); lock (_ActiveWorkersLock) ++_CountOfActiveWorkers; ThreadPool.QueueUserWorkItem(o => HandleRequest(context, productionRoutingNetwork)); } catch (Exception ex) { /* Client disconnected or some other error */ string errorString = "Error: " + ex; log.Error(errorString); Notification.SendMessageByEmail(Notification.AlarmType.ERROR, errorString); } } }
private void CreateConnection(ref SqlDataReader reader, ref RoutingNetwork Network) { TConnection Connection = null; string SourceStationID = reader["stop_id"].ToString(); string DestinationStationID = reader["next_stop_id"].ToString(); if (SourceStationID != string.Empty & Stops.ContainsKey(SourceStationID)) { if (DestinationStationID != string.Empty & Stops.ContainsKey(DestinationStationID)) { TNode SourceStation = Stops[SourceStationID]; TNode DestinationStation = Stops[DestinationStationID]; // int srcArrivalTime = Globals.ConvertTimeToSeconds(reader["arrival_time"].ToString()); int srcDepartureTime = Globals.ConvertTimeToSeconds(reader["departure_time"].ToString()); int dstArrivalTime = Globals.ConvertTimeToSeconds(reader["next_arrival_time"].ToString()); int dstDepartureTime = Globals.ConvertTimeToSeconds(reader["next_departure_time"].ToString()); //----------------------------------------------------------------------------------- //Connection = Network.AreConnected(SourceStation, DestinationStation, reader["route_id"].ToString()); Connection = null; if (Connection == null) { Connection = Network.AddConnection(SourceStation, DestinationStation); } //------------------------------------------------------------------------------------ Connection.AddTimeTableEntry( new TimeTableEntry(srcArrivalTime, srcDepartureTime, dstArrivalTime, dstDepartureTime, reader["route_id"].ToString(), reader["route_long_name"].ToString(), reader["route_short_name"].ToString(), reader["route_desc"].ToString(), reader["route_type"].ToString(), reader["route_url"].ToString(), reader["trip_id"].ToString(), reader["service_id"].ToString(), GetDates(reader["service_id"].ToString()), reader["agency_id"].ToString()) ); } } }
public static FeatureCollection GetFeatures(this RouterDb db) { RoutingNetwork network = db.Network; FeatureCollection featureCollection = new FeatureCollection(); HashSet <long> longSet = new HashSet <long>(); RoutingNetwork.EdgeEnumerator edgeEnumerator = network.GetEdgeEnumerator(); for (uint vertex1 = 0; vertex1 < network.VertexCount; ++vertex1) { GeoCoordinateSimple vertex2 = network.GeometricGraph.GetVertex(vertex1); featureCollection.Add(new Feature((Geometry) new Point(new GeoCoordinate((double)vertex2.Latitude, (double)vertex2.Longitude)), (GeometryAttributeCollection) new SimpleGeometryAttributeCollection((IEnumerable <Tag>) new Tag[1] { Tag.Create("id", vertex1.ToInvariantString()) }))); edgeEnumerator.MoveTo(vertex1); edgeEnumerator.Reset(); while (edgeEnumerator.MoveNext()) { if (!longSet.Contains((long)edgeEnumerator.Id)) { longSet.Add((long)edgeEnumerator.Id); List <ICoordinate> shape = network.GetShape(edgeEnumerator.Current); List <GeoCoordinate> geoCoordinateList = new List <GeoCoordinate>(); foreach (ICoordinate coordinate in shape) { geoCoordinateList.Add(new GeoCoordinate((double)coordinate.Latitude, (double)coordinate.Longitude)); } LineString lineString = new LineString((IEnumerable <GeoCoordinate>)geoCoordinateList); TagsCollectionBase profileAndMeta = db.GetProfileAndMeta((uint)edgeEnumerator.Data.Profile, edgeEnumerator.Data.MetaId); profileAndMeta.AddOrReplace(Tag.Create("id", edgeEnumerator.Id.ToInvariantString())); featureCollection.Add(new Feature((Geometry)lineString, (GeometryAttributeCollection) new SimpleGeometryAttributeCollection((IEnumerable <Tag>)profileAndMeta))); } } } return(featureCollection); }
/// <summary> /// Creates a new network optimizer algorithm. /// </summary> public ZeroLengthLinksOptimizer(RoutingNetwork network, CanRemoveDelegate canRemove) { _network = network; _canRemove = canRemove; }
private void GetTimetableData(ref RoutingNetwork Network, Point MinPoint, Point MaxPoint) { if (DBConnection.OpenConnection()) { SqlCommand cmd = new SqlCommand(); SqlCommand cmd2 = new SqlCommand(); SqlDataReader reader; cmd.Connection = DBConnection.Connection; cmd2.Connection = DBConnection.Connection; /* * This query constructs for every route and trip the direct connections * from one station to the next. The arrival and departure time of the source station * with the stop sequence included, and the same for the destination station. */ cmd.CommandText = "SELECT T1.route_id, route_long_name, route_short_name, route_desc, route_type, route_url, agency_id, T1.trip_id, T1.service_id," + "T1.stop_id, T1.arrival_time, T1.departure_time, T1.stop_sequence, " + "T2.stop_id AS 'next_stop_id', T2.arrival_time AS 'next_arrival_time', " + "T2.departure_time AS 'next_departure_time', T2.stop_sequence AS 'next_stop_sequence' " + "FROM " + "( " + "SELECT trips.route_id, stop_times.trip_id, arrival_time, departure_time, stop_id, stop_sequence, trips.service_id " + "FROM trips " + "INNER JOIN stop_times ON stop_times.trip_id = trips.trip_id " + "WHERE stop_id in ( " + "SELECT stop_id " + "FROM stops " + "WHERE (stop_lat BETWEEN @min_lat AND @max_lat) AND (stop_lon BETWEEN @min_lon AND @max_lon) " + ") " + ") AS T1 " + "INNER JOIN " + "( " + "SELECT trips.route_id, stop_times.trip_id, arrival_time, departure_time, " + "stop_id, stop_sequence " + "FROM trips " + "INNER JOIN stop_times ON stop_times.trip_id = trips.trip_id " + "WHERE stop_id in ( " + "SELECT stop_id " + "FROM stops " + "WHERE (stop_lat BETWEEN @min_lat AND @max_lat) AND (stop_lon BETWEEN @min_lon AND @max_lon) " + ") " + ") AS T2 " + "ON T1.route_id = T2.route_id AND T1.trip_id = T2.trip_id AND T2.stop_sequence = T1.stop_sequence + 1 " + "INNER JOIN routes ON T1.route_id = routes.route_id"; // cmd.Parameters.Add(new SqlParameter("@min_lat", System.Data.SqlDbType.Real)).Value = MinPoint.Latitude; cmd.Parameters.Add(new SqlParameter("@max_lat", System.Data.SqlDbType.Real)).Value = MaxPoint.Latitude; cmd.Parameters.Add(new SqlParameter("@min_lon", System.Data.SqlDbType.Real)).Value = MinPoint.Longitude; cmd.Parameters.Add(new SqlParameter("@max_lon", System.Data.SqlDbType.Real)).Value = MaxPoint.Longitude; // cmd2.CommandText = "select count(*) from (" + cmd.CommandText + ") as tab"; cmd2.Parameters.Add(new SqlParameter("@min_lat", System.Data.SqlDbType.Real)).Value = MinPoint.Latitude; cmd2.Parameters.Add(new SqlParameter("@max_lat", System.Data.SqlDbType.Real)).Value = MaxPoint.Latitude; cmd2.Parameters.Add(new SqlParameter("@min_lon", System.Data.SqlDbType.Real)).Value = MinPoint.Longitude; cmd2.Parameters.Add(new SqlParameter("@max_lon", System.Data.SqlDbType.Real)).Value = MaxPoint.Longitude; cmd2.CommandType = System.Data.CommandType.Text; cmd2.CommandTimeout = int.MaxValue; reader = cmd2.ExecuteReader(); reader.Read(); int recs = (int)reader[0]; log.Info("Total records to be processed: " + recs); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandTimeout = int.MaxValue; reader = cmd.ExecuteReader(); //while (reader.read()) //{ // createconnection(ref reader, ref network); //} //reader.close(); int ITER = 0; while (reader.Read()) { ITER++; if ((ITER % 10000) == 0) { log.Info("Building connection " + ITER + " (" + (int)(ITER * 100 / recs) + "%)"); // iter : x = recs : 100 } CreateConnection(ref reader, ref Network); } log.Info("Connections built"); reader.Close(); } DBConnection.CloseConnection(); }
public void AddCoreEdge(uint vertex1, uint vertex2, EdgeData data, List <ICoordinate> shape) { if ((double)data.Distance < (double)this._db.Network.MaxEdgeDistance) { int num1 = (int)this._db.Network.AddEdge(vertex1, vertex2, data, (IEnumerable <ICoordinate>)shape); } else { if (shape == null) { shape = new List <ICoordinate>(); } shape = new List <ICoordinate>((IEnumerable <ICoordinate>)shape); shape.Insert(0, (ICoordinate)this._db.Network.GetVertex(vertex1)); shape.Add((ICoordinate)this._db.Network.GetVertex(vertex2)); for (int index = 1; index < shape.Count; ++index) { if (GeoCoordinate.DistanceEstimateInMeter(shape[index - 1], shape[index]) >= (double)this._db.Network.MaxEdgeDistance) { shape.Insert(index, (ICoordinate) new GeoCoordinateSimple() { Latitude = (float)(((double)shape[index - 1].Latitude + (double)shape[index].Latitude) / 2.0), Longitude = (float)(((double)shape[index - 1].Longitude + (double)shape[index].Longitude) / 2.0) }); --index; } } int num2 = 0; List <ICoordinate> coordinateList1 = new List <ICoordinate>(); float num3 = 0.0f; int index1 = num2 + 1; EdgeData edgeData; while (index1 < shape.Count) { float num4 = (float)GeoCoordinate.DistanceEstimateInMeter(shape[index1 - 1], shape[index1]); if ((double)num4 + (double)num3 > (double)this._db.Network.MaxEdgeDistance) { ICoordinate coordinate = coordinateList1[coordinateList1.Count - 1]; coordinateList1.RemoveAt(coordinateList1.Count - 1); uint vertexCount = this._db.Network.VertexCount; this._db.Network.AddVertex(vertexCount, coordinate.Latitude, coordinate.Longitude); RoutingNetwork network = this._db.Network; int num5 = (int)vertex1; int num6 = (int)vertexCount; edgeData = new EdgeData(); edgeData.Distance = num3; edgeData.MetaId = data.MetaId; edgeData.Profile = data.Profile; EdgeData data1 = edgeData; List <ICoordinate> coordinateList2 = coordinateList1; int num7 = (int)network.AddEdge((uint)num5, (uint)num6, data1, (IEnumerable <ICoordinate>)coordinateList2); vertex1 = vertexCount; coordinateList1.Clear(); coordinateList1.Add(shape[index1]); num3 = num4; ++index1; } else { coordinateList1.Add(shape[index1]); num3 += num4; ++index1; } } if (coordinateList1.Count > 0) { coordinateList1.RemoveAt(coordinateList1.Count - 1); } RoutingNetwork network1 = this._db.Network; int num8 = (int)vertex1; int num9 = (int)vertex2; edgeData = new EdgeData(); edgeData.Distance = num3; edgeData.MetaId = data.MetaId; edgeData.Profile = data.Profile; EdgeData data2 = edgeData; List <ICoordinate> coordinateList3 = coordinateList1; int num10 = (int)network1.AddEdge((uint)num8, (uint)num9, data2, (IEnumerable <ICoordinate>)coordinateList3); } }
/// <summary> /// Deserializes a database from the given stream. /// </summary> public static RouterDb Deserialize(Stream stream, RouterDbProfile profile) { // deserialize all basic data. // version1: OsmSharp.Routing state of layout. // version2: Added ShortcutsDbs. // version3: Add advanced profile serialization. // version4: Added missing restriction dbs. var version = stream.ReadByte(); if (version != 1 && version != 2 && version != 3 && version != 4) { throw new Exception(string.Format("Cannot deserialize routing db: Invalid version #: {0}.", version)); } var guidBytes = new byte[16]; stream.Read(guidBytes, 0, 16); var guid = new Guid(guidBytes); var supportedVehicleInstances = new List <Vehicle>(); if (version <= 2) { // just contains vehicle names. var supportedVehicles = stream.ReadWithSizeStringArray(); foreach (var vehicleName in supportedVehicles) { Profile vehicleProfile; if (Profile.TryGet(vehicleName, out vehicleProfile)) { supportedVehicleInstances.Add(vehicleProfile.Parent); } else { Itinero.Logging.Logger.Log("RouterDb", Logging.TraceEventType.Warning, "Vehicle with name {0} was not found, register all vehicle profiles before deserializing the router db.", vehicleName); } } } else { // contains the full vehicles. var lengthBytes = new byte[4]; stream.Read(lengthBytes, 0, 4); var size = BitConverter.ToInt32(lengthBytes, 0); for (var i = 0; i < size; i++) { var vehicle = Vehicle.Deserialize(stream); supportedVehicleInstances.Add(vehicle); vehicle.Register(); } } var metaDb = stream.ReadWithSizeAttributesCollection(); var shorcutsCount = (int)0; if (version >= 2) { // when version < 1 there are no shortcuts and thus no shortcut count. shorcutsCount = stream.ReadByte(); } var contractedCount = stream.ReadByte(); var restrictionDbCount = 0; if (version >= 4) { restrictionDbCount = stream.ReadByte(); } var profiles = AttributesIndex.Deserialize(new LimitedStream(stream), true); var meta = AttributesIndex.Deserialize(new LimitedStream(stream), true); var network = RoutingNetwork.Deserialize(stream, profile == null ? null : profile.RoutingNetworkProfile); // create router db. var routerDb = new RouterDb(guid, network, profiles, meta, metaDb, supportedVehicleInstances.ToArray()); // read all shortcut dbs. for (var i = 0; i < shorcutsCount; i++) { var shortcutsName = stream.ReadWithSizeString(); var shorcutsDb = ShortcutsDb.Deserialize(stream); routerDb._shortcutsDbs[shortcutsName] = shorcutsDb; } // read all contracted versions. for (var i = 0; i < contractedCount; i++) { var profileName = stream.ReadWithSizeString(); var contracted = ContractedDb.Deserialize(stream, profile == null ? null : profile.ContractedDbProfile); routerDb._contracted[profileName] = contracted; } // read all restriction dbs. for (var i = 0; i < restrictionDbCount; i++) { var restrictionDbName = stream.ReadWithSizeString(); var restrictionDb = RestrictionsDb.Deserialize(stream, profile == null ? null : profile.RestrictionDbProfile); routerDb._restrictionDbs[restrictionDbName] = restrictionDb; } return(routerDb); }
public static void Sort(this RoutingNetwork graph) { graph.Sort(Hilbert.DefaultHilbertSteps); }
public NetworkOptimizer(RoutingNetwork network, NetworkOptimizer.MergeDelegate merge) { this._network = network; this._merge = merge; }
/// <summary> /// Gets all features. /// </summary> /// <returns></returns> public static FeatureCollection GetFeatures(this RoutingNetwork network) { return(network.GetFeaturesIn(float.MinValue, float.MinValue, float.MaxValue, float.MaxValue)); }
public ZeroLengthLinksOptimizer(RoutingNetwork network, ZeroLengthLinksOptimizer.CanRemoveDelegate canRemove) { this._network = network; this._canRemove = canRemove; }
/// <summary> /// Creates a new network optimizer algorithm. /// </summary> public NetworkOptimizer(RoutingNetwork network, MergeDelegate merge) { _network = network; _merge = merge; }
public void TestTwoIdenticalEdgesWithShapes() { var graph = new RoutingNetwork(new Itinero.Graphs.Geometric.GeometricGraph(1, 2)); graph.AddVertex(0, 0, 0); graph.AddVertex(1, 1, 1); graph.AddVertex(2, 2, 2); graph.AddEdge(0, 1, new EdgeData() { Profile = 1 }, new Coordinate(0.5f, 0.5f)); graph.AddEdge(1, 2, new EdgeData() { Profile = 1 }, new Coordinate(1.5f, 1.5f)); // execute algorithm. var algorithm = new NetworkOptimizer(graph, MergeDelegate); algorithm.Run(); // check result. var edges = graph.GetEdgeEnumerator(0); Assert.AreEqual(1, edges.Count()); Assert.AreEqual(1, edges.First().Data.Profile); var shape = new List <Coordinate>(edges.Shape); Assert.AreEqual(3, shape.Count); Assert.AreEqual(0.5, shape[0].Latitude); Assert.AreEqual(0.5, shape[0].Longitude); Assert.AreEqual(1, shape[1].Latitude); Assert.AreEqual(1, shape[1].Longitude); Assert.AreEqual(1.5, shape[2].Latitude); Assert.AreEqual(1.5, shape[2].Longitude); graph = new RoutingNetwork(new Itinero.Graphs.Geometric.GeometricGraph(1, 2)); graph.AddVertex(0, 0, 0); graph.AddVertex(1, 1, 1); graph.AddVertex(2, 2, 2); graph.AddEdge(1, 0, new EdgeData() { Profile = 1 }, new Coordinate(0.5f, 0.5f)); graph.AddEdge(1, 2, new EdgeData() { Profile = 1 }, new Coordinate(1.5f, 1.5f)); // execute algorithm. algorithm = new NetworkOptimizer(graph, MergeDelegate); algorithm.Run(); // check result. edges = graph.GetEdgeEnumerator(0); Assert.AreEqual(1, edges.Count()); Assert.AreEqual(1, edges.First().Data.Profile); shape = new List <Coordinate>(edges.Shape); Assert.AreEqual(3, shape.Count); Assert.AreEqual(0.5, shape[0].Latitude); Assert.AreEqual(0.5, shape[0].Longitude); Assert.AreEqual(1, shape[1].Latitude); Assert.AreEqual(1, shape[1].Longitude); Assert.AreEqual(1.5, shape[2].Latitude); Assert.AreEqual(1.5, shape[2].Longitude); graph = new RoutingNetwork(new Itinero.Graphs.Geometric.GeometricGraph(1, 2)); graph.AddVertex(0, 0, 0); graph.AddVertex(1, 1, 1); graph.AddVertex(2, 2, 2); graph.AddEdge(1, 0, new EdgeData() { Profile = 1 }, new Coordinate(0.5f, 0.5f)); graph.AddEdge(2, 1, new EdgeData() { Profile = 1 }, new Coordinate(1.5f, 1.5f)); // execute algorithm. algorithm = new NetworkOptimizer(graph, MergeDelegate); algorithm.Run(); // check result. edges = graph.GetEdgeEnumerator(0); Assert.AreEqual(1, edges.Count()); Assert.AreEqual(1, edges.First().Data.Profile); Assert.AreEqual(true, edges.First().DataInverted); shape = new List <Coordinate>(edges.Shape); Assert.AreEqual(3, shape.Count); Assert.AreEqual(1.5, shape[0].Latitude); Assert.AreEqual(1.5, shape[0].Longitude); Assert.AreEqual(1, shape[1].Latitude); Assert.AreEqual(1, shape[1].Longitude); Assert.AreEqual(0.5, shape[2].Latitude); Assert.AreEqual(0.5, shape[2].Longitude); }
public TrafficParser(RoutingNetwork network, List <TrafficReport> TrafficReport) { RoadNetwork = network; this.TrafficReport = TrafficReport; }
static void Main(string[] args) { log.Info("Application starts"); string host = ConfigurationManager.AppSettings["host"]; string port = ConfigurationManager.AppSettings["port"]; string service = ConfigurationManager.AppSettings["service"]; string protocol = ConfigurationManager.AppSettings["protocol"]; bool CarpoolingEnabled = bool.Parse(ConfigurationManager.AppSettings["CarpoolingEnabled"]); bool TrafficEnabled = bool.Parse(ConfigurationManager.AppSettings["TrafficEnabled"]); double TrafficPropagationMaxDistance = float.Parse(ConfigurationManager.AppSettings["TrafficPropagationMaxDistance"]); int CarpoolingMaxConnectionsPerTNode = int.Parse(ConfigurationManager.AppSettings["CarpoolingMaxConnectionsPerTNode"]); /* This variable is used to decide if update at startup the external carpooling rides to the network or wait the midnight */ bool updateExtRidesAtStartup = bool.Parse(ConfigurationManager.AppSettings["ExtCarpoolingRideUpdateAtStartup"]); //var host = Dns.GetHostAddresses(Dns.GetHostName())[0]; string url = protocol + "://" + host + ":" + port + service; log.Info(url); Notification.SendMessageByEmail(Notification.AlarmType.INFO, DateTime.Now.ToString() + "\r\nWebAPI starts at " + url + "\r\nBuilding network..."); /* Get the site timeZone from the GTFS data (needed for the carpooling date caonversion) */ string timeZone = null; timeZone = DBParser.GetTimeZoneFromAgencyTable(); /* Get the boundaries from the OSM Map (needed for the backend carpooling http requests) */ Point MapMinPoint = null, MapMaxPoint = null; string OSMXMLMapFilePath = System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["dataPath"] + ConfigurationManager.AppSettings["OSMXMLMapFile"]); log.Info("Parsing " + OSMXMLMapFilePath + " OSM."); routingNetwork1 = new Routing.RoutingNetwork(); OSM.XMLParser Parser = new OSM.XMLParser(); Parser.GetBoundaries(OSMXMLMapFilePath, ref MapMinPoint, ref MapMaxPoint); if ((MapMinPoint != null) && (MapMaxPoint != null)) { log.Info("Map Boundaries: minlat:" + MapMinPoint.Latitude + ", minlon:" + MapMinPoint.Longitude + ", maxlat:" + MapMaxPoint.Latitude + ", maxlon:" + MapMaxPoint.Longitude); } else { string message = "Application ends\r\nMap boundaries not found into the OSM map: minlat:" + MapMinPoint.Latitude + ", minlon:" + MapMinPoint.Longitude + ", maxlat:" + MapMaxPoint.Latitude + ", maxlon:" + MapMaxPoint.Longitude; log.Error(message); Notification.SendMessageByEmail(Notification.AlarmType.ERROR, DateTime.Now.ToString() + "\r\n" + message); Environment.Exit(0); } /* Get the dynamic data version from the backend web service */ DynamicData = HTTPRequests.getDynamicDataVersionFromBackend(MapMinPoint, MapMaxPoint); if (DynamicData != null) { if (CarpoolingEnabled) { /* Set the Carpooling data version */ CarPooling.Version = new CarpoolerVersion(DynamicData.sites.First().carpooling_info.version, DynamicData.sites.First().carpooling_info.updated, DynamicData.sites.First().name, DynamicData.sites.First().carpooling_info.nightly_version, DynamicData.sites.First().carpooling_info.nightly_updated); log.Info("CARPOOLING Version:" + CarPooling.Version.version + " Timestamp:" + CarPooling.Version.timestampVersion + " NightlyVersion:" + CarPooling.Version.nightly_version + " NightlyTimestamp: " + CarPooling.Version.nightly_timestampVersion); bool updateExternalRides = false; if ((updateExtRidesAtStartup) || ((DateTime.Now.Hour < ExtCarpoolingAvailableUpdateTimeFrom) && (DateTime.Now.Hour >= ExtCarpoolingAvailableUpdateTimeTo))) { updateExternalRides = true; } /* Get the carpooling rides list from the backend web service */ CarPooling.Carpoolers = HTTPRequests.getCarpoolingDataFromBackend(MapMinPoint, MapMaxPoint, updateExternalRides); } if (TrafficEnabled) { /* Set the Traffic/incidents data version */ Traffic.Version = new TrafficVersion(DynamicData.sites.First().reports_info.version, DynamicData.sites.First().reports_info.updated, DynamicData.sites.First().name); log.Info("TRAFFIC Version:" + Traffic.Version.version + " Timestamp:" + Traffic.Version.timestampVersion); /* Get the Traffic/incidents data from the backend web service */ Traffic.TrafficReport = HTTPRequests.getTrafficDataFromBackend(MapMinPoint, MapMaxPoint, TrafficPropagationMaxDistance); } } /* Build the network */ routingNetwork1 = RoutePlanner.Globals.BuildNetwork(ref CParser, ref TParser, CarPooling.Carpoolers, Traffic.TrafficReport, TrafficPropagationMaxDistance, CarpoolingMaxConnectionsPerTNode); /* Copy the network */ //routingNetwork2 = new RoutingNetwork { }; //routingNetwork1.duplicateNetwork(ref routingNetwork2); log.Info("Starting server at " + url); Notification.SendMessageByEmail(Notification.AlarmType.INFO, DateTime.Now.ToString() + "\r\nService is running at " + url); HTTPAsyncServer Server = new HTTPAsyncServer(url); log.Error("Application ends"); Notification.SendMessageByEmail(Notification.AlarmType.ERROR, "Application ends"); }
/// <summary> /// Creates a router point for the given vertex. /// </summary> public static RouterPoint CreateRouterPointForVertex(this RoutingNetwork graph, uint vertex, uint neighbour) { return(graph.GeometricGraph.CreateRouterPointForVertex(vertex, neighbour)); }