Compare commits

..

5 Commits

Author SHA1 Message Date
72b5511c26 better readability 2023-04-06 02:32:04 +02:00
f42e458048 Created GetSpeed method for uniform implementation
Changed Pathfinding class to static
Changed AStar to continue after path found.
2023-04-06 02:23:12 +02:00
3e23635cd1 Serialize Path for API 2023-04-06 02:22:03 +02:00
ed8558049c Added first API. 2023-04-06 01:29:45 +02:00
20d4da9e6f Changed to JsonSerialization to permanently store regions. 2023-04-06 01:29:30 +02:00
16 changed files with 244 additions and 66 deletions

22
API/API.csproj Normal file
View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Controllers" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Pathfinding\Pathfinding.csproj" />
</ItemGroup>
</Project>

37
API/Program.cs Normal file
View File

@ -0,0 +1,37 @@
using OSMDatastructure.Graph;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.MapGet("/getRoute", (float latStart, float lonStart, float latEnd, float lonEnd) =>
{
List<OsmNode> path = Pathfinding.Pathfinder.CustomAStar("D:/stuttgart-regbez-latest", new Coordinates(latStart, lonStart), new Coordinates(latEnd, lonEnd),
Tag.SpeedType.car);
return path;
}
);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,41 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:39952",
"sslPort": 44326
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5057",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7095;http://localhost:5057",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

9
API/appsettings.json Normal file
View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -1,4 +1,5 @@
using System.Globalization;
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
@ -8,6 +9,7 @@ public class Coordinates
public float latitude { get; }
public float longitude { get; }
[JsonConstructor]
public Coordinates(float latitude, float longitude)
{
this.latitude = latitude;

View File

@ -6,4 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.Serialization.Json" Version="4.3.0" />
</ItemGroup>
</Project>

View File

@ -1,3 +1,5 @@
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
[Serializable]
@ -9,6 +11,7 @@ public class OsmEdge
public ulong neighborRegion { get; }
[JsonConstructor]
public OsmEdge(ulong wayId, ulong startId, ulong neighborId, ulong neighborRegion)
{
this.wayId = wayId;

View File

@ -1,5 +1,6 @@
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
@ -7,13 +8,13 @@ namespace OSMDatastructure.Graph;
public class OsmNode
{
public ulong nodeId { get; }
public HashSet<OsmEdge> edges { get; }
public HashSet<OsmEdge> edges { get; set; }
public Coordinates coordinates { get; }
[NonSerialized]public OsmNode? previousPathNode = null;
[NonSerialized]public double currentPathWeight = double.MaxValue;
[NonSerialized]public double currentPathLength = double.MaxValue;
[NonSerialized]public double directDistanceToGoal = double.MaxValue;
[JsonIgnore][NonSerialized]public OsmNode? previousPathNode = null;
[JsonInclude][NonSerialized]public double currentPathWeight = double.MaxValue;
[JsonInclude][NonSerialized]public double currentPathLength = double.MaxValue;
[JsonIgnore][NonSerialized]public double directDistanceToGoal = double.MaxValue;
[OnDeserialized]
internal void SetDefaultValues(StreamingContext context)
@ -30,6 +31,7 @@ public class OsmNode
this.coordinates = new Coordinates(lat, lon);
}
[JsonConstructor]
public OsmNode(ulong nodeId, Coordinates coordinates)
{
this.nodeId = nodeId;

View File

@ -1,4 +1,5 @@
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
using System.Text.Json.Serialization;
using OSMDatastructure.Graph;
namespace OSMDatastructure;
@ -6,21 +7,32 @@ namespace OSMDatastructure;
[Serializable]
public class Region
{
[NonSerialized]public const float RegionSize = 0.025f;
public readonly HashSet<OsmNode> nodes = new();
public ulong regionHash { get; }
public TagManager tagManager { get; }
[JsonIgnore]public const float RegionSize = 0.025f;
[JsonIgnore]public static readonly JsonSerializerOptions serializerOptions = new()
{
IncludeFields = true,
MaxDepth = 32,
IgnoreReadOnlyFields = false//,
//WriteIndented = true
};
[JsonRequired]public HashSet<OsmNode> nodes { get; set; }
public ulong regionHash { get; }
[JsonRequired]public TagManager tagManager { get; set; }
[JsonConstructor]
public Region(ulong regionHash)
{
this.regionHash = regionHash;
tagManager = new TagManager();
nodes = new HashSet<OsmNode>();
}
public Region(Coordinates coordinates)
{
regionHash = Coordinates.GetRegionHashCode(coordinates);
tagManager = new TagManager();
nodes = new HashSet<OsmNode>();
}
public bool ContainsNode(ulong id)
@ -49,11 +61,8 @@ public class Region
public static Region? FromFile(string filePath)
{
BinaryFormatter bFormatter = new BinaryFormatter();
#pragma warning disable SYSLIB0011
if (File.Exists(filePath))
return (Region)bFormatter.Deserialize(new FileStream(filePath, FileMode.Open));
#pragma warning restore SYSLIB0011
return JsonSerializer.Deserialize<Region>(new FileStream(filePath, FileMode.Open), serializerOptions)!;
else return null;
}

View File

@ -1,3 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
[Serializable]
@ -6,11 +9,36 @@ public class Tag
public TagType key { get; }
public dynamic value { get; }
[JsonConstructor]
public Tag(TagType key, dynamic value)
{
this.key = key;
this.value = value;
if (value is JsonElement)
{
switch (key)
{
case TagType.highway:
this.value = (WayType)value.GetByte();
break;
case TagType.maxspeed:
this.value = value.GetByte();
break;
case TagType.forward:
case TagType.oneway:
this.value = value.GetBoolean();
break;
case TagType.id:
this.value = value.GetUInt64();
break;
default:
this.value = value;
break;
}
}
else
{
this.value = value;
}
}
public static Tag FromBytes(byte[] bytes)

View File

@ -1,11 +1,16 @@
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
[Serializable]
public class TagManager
{
public readonly Dictionary<ulong, HashSet<Tag>> wayTagSets = new();
[JsonRequired]public Dictionary<ulong, HashSet<Tag>> wayTagSets { get; set; }
public TagManager()
{
wayTagSets = new();
}
public bool ContainsKey(ulong wayId, Tag.TagType key)
{

View File

@ -6,6 +6,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OSMDatastructure", "OSMData
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Pathfinding", "Pathfinding\Pathfinding.csproj", "{D4AA1C47-98D4-415C-B026-3BC25B6B6F9D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{1D364F40-1681-4D36-A625-83B324F6AC89}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -24,5 +26,9 @@ Global
{D4AA1C47-98D4-415C-B026-3BC25B6B6F9D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4AA1C47-98D4-415C-B026-3BC25B6B6F9D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4AA1C47-98D4-415C-B026-3BC25B6B6F9D}.Release|Any CPU.Build.0 = Release|Any CPU
{1D364F40-1681-4D36-A625-83B324F6AC89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1D364F40-1681-4D36-A625-83B324F6AC89}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1D364F40-1681-4D36-A625-83B324F6AC89}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1D364F40-1681-4D36-A625-83B324F6AC89}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -4,7 +4,7 @@ using OSMImporter;
namespace Pathfinding;
public class Pathfinder
public static class Pathfinder
{
public static List<OsmNode> CustomAStar(string workingDir, Coordinates start, Coordinates goal, Tag.SpeedType vehicle)
{
@ -14,8 +14,8 @@ public class Pathfinder
if (startRegion is null || goalRegion is null)
return new List<OsmNode>();
OsmNode? startNode = ClosestNodeToCoordinates(start, startRegion, vehicle);
OsmNode? goalNode = ClosestNodeToCoordinates(goal, goalRegion, vehicle);
OsmNode? startNode = ClosestNodeToCoordinates(start, startRegion, vehicle, ref regionManager);
OsmNode? goalNode = ClosestNodeToCoordinates(goal, goalRegion, vehicle, ref regionManager);
if (startNode == null || goalNode == null)
return new List<OsmNode>();
@ -27,7 +27,7 @@ public class Pathfinder
OsmNode closestNodeToGoal = startNode;
bool stop = false;
while (toVisit.Count > 0 && !stop)
while (toVisit.Count > 0)
{
closestNodeToGoal = toVisit.Dequeue();
Console.WriteLine($"{toVisit.Count:000} {closestNodeToGoal.directDistanceToGoal:#.00} current:{closestNodeToGoal}");
@ -39,15 +39,18 @@ public class Pathfinder
{
double newPotentialWeight =
closestNodeToGoal.currentPathWeight + EdgeWeight(closestNodeToGoal, neighbor, edge.wayId, vehicle, ref regionManager);
if (neighbor.currentPathWeight > newPotentialWeight)
if (newPotentialWeight < neighbor.currentPathWeight)
{
neighbor.previousPathNode = closestNodeToGoal;
neighbor.currentPathWeight = newPotentialWeight;
neighbor.currentPathLength = closestNodeToGoal.currentPathLength + Utils.DistanceBetween(closestNodeToGoal, neighbor);
if (neighbor.Equals(goalNode) || closestNodeToGoal.directDistanceToGoal < 10) //change for faster
if (neighbor.Equals(goalNode) || closestNodeToGoal.directDistanceToGoal < 10)
{
stop = true;
else
goalNode = neighbor;
}
else if(!stop)
{
neighbor.directDistanceToGoal = Utils.DistanceBetween(neighbor, goalNode);
toVisit.Enqueue(neighbor, neighbor.directDistanceToGoal);
@ -58,7 +61,7 @@ public class Pathfinder
}
List<OsmNode> path = new();
OsmNode? currentNode = closestNodeToGoal;
OsmNode? currentNode = goalNode;
while (currentNode != null && !currentNode.Equals(startNode))
{
path.Add(currentNode);
@ -70,33 +73,21 @@ public class Pathfinder
return path;
}
private static OsmNode? ClosestNodeToCoordinates(Coordinates coordinates, Region region, Tag.SpeedType vehicle)
private static OsmNode? ClosestNodeToCoordinates(Coordinates coordinates, Region region, Tag.SpeedType vehicle, ref RegionManager regionManager)
{
OsmNode? closest = null;
double distance = double.MaxValue;
foreach (OsmNode node in region.nodes)
{
bool hasConnection = false;
bool hasConnectionUsingVehicle = false;
foreach (OsmEdge edge in node.edges)
{
byte speed = 0;
switch (vehicle)
{
case Tag.SpeedType.road:
case Tag.SpeedType.car:
speed = Tag.defaultSpeedCar[(Tag.WayType)region.tagManager.GetTag(edge.wayId, Tag.TagType.highway)!];
break;
case Tag.SpeedType.pedestrian:
speed = Tag.defaultSpeedPedestrian[
(Tag.WayType)region.tagManager.GetTag(edge.wayId, Tag.TagType.highway)!];
break;
}
double speed = GetSpeed(node, edge.wayId, vehicle, ref regionManager);
if (speed != 0)
hasConnection = true;
hasConnectionUsingVehicle = true;
}
double nodeDistance = Utils.DistanceBetween(node, coordinates);
if (nodeDistance < distance && hasConnection)
if (nodeDistance < distance && hasConnectionUsingVehicle)
{
closest = node;
distance = nodeDistance;
@ -106,30 +97,37 @@ public class Pathfinder
return closest;
}
private static double EdgeWeight(OsmNode node1, OsmNode node2, ulong wayId, Tag.SpeedType vehicle, ref RegionManager regionManager)
private static double GetSpeed(OsmNode node1, ulong wayId, Tag.SpeedType vehicle, ref RegionManager regionManager)
{
TagManager tags = regionManager.GetRegion(node1.coordinates)!.tagManager;
double distance = Utils.DistanceBetween(node1, node2);
Tag.WayType wayType = (Tag.WayType)tags.GetTag(wayId, Tag.TagType.highway)!;
switch (vehicle)
{
case Tag.SpeedType.pedestrian:
byte speed = Tag.defaultSpeedPedestrian[wayType];
if(speed is not 0)
return distance / speed;
else return Double.PositiveInfinity;
if (speed is not 0)
return speed;
return 0;
case Tag.SpeedType.car:
case Tag.SpeedType.road:
byte? maxspeed = (byte?)tags.GetTag(wayId, Tag.TagType.maxspeed);
if (maxspeed is not null)
return distance / Convert.ToDouble(maxspeed);
else
maxspeed = Tag.defaultSpeedCar[wayType];
if(maxspeed is not 0)
return distance / Tag.defaultSpeedCar[wayType];
else return Double.PositiveInfinity;;
byte? maxSpeed = (byte?)tags.GetTag(wayId, Tag.TagType.maxspeed);
if (maxSpeed is not null)
return (double)maxSpeed;
maxSpeed = Tag.defaultSpeedCar[wayType];
if(maxSpeed is not 0)
return (byte)maxSpeed;
return 0;
default:
return double.PositiveInfinity;
return 0;
}
}
private static double EdgeWeight(OsmNode node1, OsmNode node2, ulong wayId, Tag.SpeedType vehicle, ref RegionManager regionManager)
{
double distance = Utils.DistanceBetween(node1, node2);
double speed = GetSpeed(node1, wayId, vehicle, ref regionManager);
if (speed is not 0)
return distance / speed;
return double.PositiveInfinity;
}
}

View File

@ -1,5 +1,6 @@
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
using System.Xml;
using OSMDatastructure;
using OSMDatastructure.Graph;
@ -46,7 +47,6 @@ public class RegionConverter
private static Dictionary<ulong, ulong> GetNodesAndRegions(XmlReader xmlReader, string outputPath)
{
BinaryFormatter bFormatter = new BinaryFormatter();
Dictionary<ulong, ulong> nodeRegions = new();
Dictionary<ulong, FileStream> regionFileStreams = new();
Dictionary<ulong, OsmNode> tmpAllNodes = new();
@ -82,6 +82,7 @@ public class RegionConverter
foreach (ulong nodeId in currentIds.Where(key => tmpAllNodes.ContainsKey(key)))
{
BinaryFormatter bFormatter = new BinaryFormatter();
if (isHighway)
{
ulong regionHash = Coordinates.GetRegionHashCode(tmpAllNodes[nodeId].coordinates);
@ -97,7 +98,7 @@ public class RegionConverter
regionFileStreams.Add(regionHash, nodesRegionStream);
}
nodeRegions.Add(nodeId, regionHash);
#pragma warning disable SYSLIB0011 //eheheh
bFormatter.Serialize(nodesRegionStream, tmpAllNodes[nodeId]);
#pragma warning restore SYSLIB0011
@ -221,7 +222,6 @@ public class RegionConverter
private static void CombineTmpFiles(string folderPath, HashSet<ulong> regionHashes)
{
BinaryFormatter bFormatter = new BinaryFormatter();
foreach (ulong regionId in regionHashes)
{
ValueTuple<Region, HashSet<OsmEdge>> tmpRegion = LoadRegion(folderPath, regionId);
@ -233,11 +233,11 @@ public class RegionConverter
startNode.edges.Add(edge);
}
}
FileStream tmpRegionFileStream = new FileStream(Path.Join(folderPath, $"{regionId}{RegionsFileName}"), FileMode.Create);
#pragma warning disable SYSLIB0011
bFormatter.Serialize(tmpRegionFileStream, tmpRegion.Item1);
#pragma warning restore SYSLIB0011
tmpRegionFileStream.Dispose();
using (FileStream tmpRegionFileStream = new FileStream(Path.Join(folderPath, $"{regionId}{RegionsFileName}"), FileMode.Create))
{
JsonSerializer.Serialize(tmpRegionFileStream, tmpRegion.Item1, typeof(Region), Region.serializerOptions);
}
Directory.Delete(Path.Join(folderPath, regionId.ToString()), true);
}
}

View File

@ -11,4 +11,8 @@
<ProjectReference Include="..\Pathfinding\Pathfinding.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.Serialization.Json" Version="4.3.0" />
</ItemGroup>
</Project>