Compare commits

...

103 Commits

Author SHA1 Message Date
56ac9dc948 unnecessary type-conversion. 2023-05-17 19:19:40 +02:00
9ef63c9886 Make it more clear what is being returned as string. 2023-05-17 19:14:36 +02:00
2b5dd91335 floating point comparison 2023-05-17 19:13:31 +02:00
9f0d47ed59 Combine statements 2023-05-17 19:08:10 +02:00
371989b34d Make GetRegion more readable / Less convoluted and complicated due to multithreading. 2023-05-17 19:06:48 +02:00
e53d1086cc TKey can not be null. 2023-05-17 19:01:00 +02:00
dc98fb51b1 Make RPriorityQueue.Count point directly to the queue.Count instead of manually updating every operation. 2023-05-17 19:00:47 +02:00
3077b4d8b8 Added abstract Renderer class that SVGRenderer and PNGRenderer inherit from.
This way standardized rendering methods can be implemented.
2023-05-16 20:00:18 +02:00
7c5d87ca76 Moved Bounds to seperate Class 2023-05-15 14:07:04 +02:00
a5f272dfb9 Removed commented Code
Added Logging to see progress
2023-05-15 13:16:41 +02:00
f84aa82186 Rename Method "FromRandomCoords" -> FromCoords 2023-05-15 13:16:11 +02:00
6d59253a0b Bounds serialization 2023-04-24 20:48:23 +02:00
af821a761f added extraTime Variable to api 2023-04-24 19:47:54 +02:00
9b88996439 added extratime variable 2023-04-24 19:39:19 +02:00
5733b0edb3 Adjusted priority render 2023-04-24 19:39:04 +02:00
923cbee280 Removed result from getshortestroute 2023-04-24 19:38:51 +02:00
f19aa0007e Testsetup for time 2023-04-24 19:38:23 +02:00
f525b88a3a Best factors for current heurisitc: roadPriority 0.0215, extraTime: 3 2023-04-24 19:38:09 +02:00
d497196f9f Added methods RemoveExcept(Ienumberable) and Clear() 2023-04-24 19:37:25 +02:00
c705fdb63a Throw exception instead of returning null when file not found. 2023-04-24 18:53:20 +02:00
aa05aad5b3 Added missing maxspeed:max 2023-04-24 18:53:02 +02:00
7d33d11a03 shortest path 2023-04-23 16:23:49 +02:00
edd931bca5 logging format 2023-04-23 16:23:06 +02:00
6b5dddb1e3 Prevent method from returning before all threads are finished.
Include calculating threads in output.
2023-04-23 16:03:39 +02:00
fea0ecf17b remove exisiting results. 2023-04-23 16:02:55 +02:00
30b29aa25c whitespace and readability 2023-04-23 15:27:23 +02:00
73e7daffd7 Formatting of finding best variables 2023-04-23 15:27:06 +02:00
7b88616373 Preload Regions 2023-04-23 15:26:29 +02:00
2799db162d readability 2023-04-23 15:09:22 +02:00
9301e948b0 Filename-formatting 2023-04-23 15:09:04 +02:00
ec6725a5c5 Removed unnecessary factors 2023-04-23 15:07:26 +02:00
886ccaa8dc removed nodeAngleFactor 2023-04-23 15:00:22 +02:00
af1d9baf4f Testsetup for cariable testing 2023-04-23 14:51:13 +02:00
e2332847cd Adjust priority in weight calculation with factor. 2023-04-23 14:50:45 +02:00
dca4d56866 Keep searching for the same amount of time already search to get shorter path. 2023-04-23 14:50:16 +02:00
5f6cccd17d Added priority queue with changable priority. 2023-04-23 14:49:09 +02:00
97a8c2ea6f Maximum turn angle variable 2023-04-23 14:48:00 +02:00
b89a3715a1 Created variable for maximum turn angle. 2023-04-23 14:47:26 +02:00
6bc1d3c7ce Adjusted API to new Pathfinder calls. 2023-04-23 14:06:19 +02:00
5b8a1d1e10 cleanup 2023-04-23 13:43:01 +02:00
7856f1c66c Changed factors to globalfields to reduce parametersin methodcall 2023-04-23 13:42:46 +02:00
97a057a3d4 Fixed gScore with MaxValue due to Vector Angle returning NaN 2023-04-23 13:41:22 +02:00
bc39785f6f Start of complete rethinking of Heuristic function and approach to get shortest path. 2023-04-23 13:11:52 +02:00
18822e2152 Changed ColorInterp 2023-04-23 13:06:47 +02:00
68cb0ee3fd Filter MaxValueWeights 2023-04-23 13:06:29 +02:00
465d40a475 Cleanup variable rename 2023-04-23 12:58:32 +02:00
7fd9047ac4 Changed Colors for weights and created variable for pointsize 2023-04-22 18:34:12 +02:00
601200a8d6 Changed imageformat 2023-04-22 18:33:34 +02:00
a758c8c63e Changed Color and thickness values 2023-04-22 17:49:59 +02:00
ed46a419e3 Moved fields for serialization. 2023-04-22 17:49:27 +02:00
a1d9ccad46 Added deserialization of PathResult 2023-04-21 18:35:02 +02:00
914731c8a3 Prevent other thread from changing collection /multithreading) 2023-04-21 18:34:49 +02:00
d8ce6e4ce5 Mutlithreaded RegionManager 2023-04-21 15:14:02 +02:00
976108569b Threadsafe for masstesting variables. 2023-04-21 15:13:42 +02:00
6373874495 Added function to render a base-area-image. 2023-04-21 14:44:50 +02:00
c43c6dc985 Cleanup
Added "sequential read" to fileoptions on deserialization.
2023-04-21 14:44:18 +02:00
33232a7eb7 Roads are now painted according to priority. 2023-04-21 14:37:38 +02:00
cf5b1e9945 Masstesting new var: Threadcount
corrected capitalization
2023-04-21 14:29:52 +02:00
aa8b1e4451 Inverse Angle 2023-04-21 14:28:02 +02:00
95c0088b73 Added function to mass-test the heuristic variables. 2023-04-21 13:49:48 +02:00
cd3905915b Cleanup 2023-04-21 13:43:50 +02:00
dd37430761 Moved RoadPriority Function to RegionManager 2023-04-21 13:41:01 +02:00
42e915ee05 Added distance and duration to PathResult. 2023-04-21 11:40:26 +02:00
7d769a064f Parallel reading of regionfiles. 2023-04-21 11:40:15 +02:00
93a448e189 Made Conversion-methods public 2023-04-21 11:01:50 +02:00
750ba5c624 Fixed angle calculation 2023-04-21 11:01:31 +02:00
1facca84ba Prevent multiple processes from reading same file. 2023-04-21 11:01:05 +02:00
8b7cfcbd77 Method for mass-testing all factors. 2023-04-21 00:43:58 +02:00
28ab2b2bb8 Added angleFactor variable 2023-04-21 00:43:38 +02:00
7201b9c993 Add turn-angle to Weight calculation.
For that added Vector-class.
Highways now have much higher priority.
2023-04-21 00:42:21 +02:00
d1f311a76b Cleanup 2023-04-21 00:41:18 +02:00
2b252e2b06 Cleanup of unnecessary code 2023-04-20 23:02:38 +02:00
d456275fc1 private field naming _cameFromDict 2023-04-20 22:58:50 +02:00
2bd6c5d9c4 Replaced local vars with fields. 2023-04-20 22:58:27 +02:00
90a09e84c5 Removed/Replaced unnecessary checks in AStar. 2023-04-20 22:53:23 +02:00
b87d8a0300 Changed calls to new backend.
Pathfinder now finds the result and returns itself.
Pathfinder includes PathResult for later usage.
2023-04-20 19:41:40 +02:00
23429c8a00 Renderer now renders 3 different layers over each other: Area (Regions), gScore-Weights (as blobs) and PathResult path.
Returns the Image instead of saving to disk.
2023-04-20 19:40:50 +02:00
946fa0206b Made Pathfinder non-static to enable field-usage in other methods/classes.
Added fields RegionManager, workingDirectory, PathResult (result of AStar), gScore (result of AStar). Fields later used in Renderer.

SaveGraph is now called SaveResult and serializes PathResult as JSON.
2023-04-20 19:39:18 +02:00
5a1dce9883 PathResult now only includes Path and calcTime.
Other fields have been moved to Pathfinder
2023-04-20 19:37:34 +02:00
619cad61ee Adjusted to new Functions and return values.
Now renders complete result with path and all loaded regions.
2023-04-19 22:55:49 +02:00
bfb117164e Added Area-render (Renders all loaded nodes and edges)
Route can now be drawn over other pictures (e.g. the area-render)
Increased resolution to 20.000
Added Bounds-Class for information exchange with image.
2023-04-19 22:53:49 +02:00
208c000577 Changed values for heuristic and weight functions, as well as increased priority for type1-roads (motorways). 2023-04-19 22:51:47 +02:00
5212e43897 Add regionManager to PathResult for internal use 2023-04-19 22:15:57 +02:00
6fb88b5c9c Include RegionManager in result for internal use 2023-04-19 22:15:43 +02:00
9e0c4f65db appropriate names in PathResult for nodes gSCoreNodes 2023-04-19 22:02:15 +02:00
055a751c9d Save Pathfinding result to file.
Load result for render.
2023-04-13 19:18:25 +02:00
08ebc9a26b Changed some display values 2023-04-13 01:12:29 +02:00
d35aab9c39 More logging 2023-04-13 01:12:16 +02:00
08e3da6fe3 Render result to png after every routing 2023-04-13 01:00:56 +02:00
367e9cfde0 Removed API 2023-04-13 01:00:38 +02:00
a70284aa87 Added visualization to confirm paths 2023-04-13 00:24:33 +02:00
13915c9773 No more use of "track" or "service" for cars. 2023-04-13 00:24:03 +02:00
c373451007 fixed missing oneway streets without "forward" tag 2023-04-13 00:18:30 +02:00
308579279b Working. Weight calculation is still wonky, as well as heuristic needing tuning. 2023-04-11 01:04:19 +02:00
2131ac4afe Still requires tuning 2023-04-10 01:33:18 +02:00
428fcb9bf8 fixed return type for tagtypes name, tagref 2023-04-10 01:33:07 +02:00
6b496957d7 Fixes for oneway-change 2023-04-09 23:55:24 +02:00
874d60992e Try improving priority 2023-04-09 22:10:58 +02:00
c1557b7678 cleanup 2023-04-09 22:10:41 +02:00
14533c150f Fixing one-way issue 2023-04-09 22:10:23 +02:00
5289020d44 correct node for closest. 2023-04-09 21:02:32 +02:00
bb789e731d Correct node for path length 2023-04-09 21:02:19 +02:00
9e72d50448 Fixed valid start and end nodes (for type) 2023-04-09 21:02:01 +02:00
27 changed files with 1023 additions and 420 deletions

View File

@ -17,6 +17,7 @@
<ItemGroup>
<ProjectReference Include="..\Pathfinding\Pathfinding.csproj" />
<ProjectReference Include="..\RenderPath\RenderPath.csproj" />
</ItemGroup>
</Project>

View File

@ -1,5 +1,3 @@
using System.Text;
using System.Text.Json.Serialization;
using OSMDatastructure;
using OSMDatastructure.Graph;
using Pathfinding;
@ -15,22 +13,20 @@ builder.Services.AddSwaggerGen();
var app = builder.Build();
app.MapGet("/getRouteDistance", (float latStart, float lonStart, float latEnd, float lonEnd) =>
app.MapGet("/getRoute", (float latStart, float lonStart, float latEnd, float lonEnd, Tag.SpeedType vehicle, double useHigherLevelRoadsPriority, double maxTurnAngle) =>
{
DateTime startCalc = DateTime.Now;
List<PathNode> result = Pathfinder.AStarDistance("D:/stuttgart-regbez-latest", new Coordinates(latStart, lonStart), new Coordinates(latEnd, lonEnd));
PathResult pathResult = new PathResult(DateTime.Now - startCalc, result);
return pathResult;
Pathfinder result = new Pathfinder("D:/stuttgart-regbez-latest", useHigherLevelRoadsPriority, maxTurnAngle).AStar(new Coordinates(latStart, lonStart),
new Coordinates(latEnd, lonEnd), vehicle, 3);
return result.pathResult;
}
);
app.MapGet("/getRouteTime", (float latStart, float lonStart, float latEnd, float lonEnd, Tag.SpeedType vehicle) =>
app.MapGet("/getShortestRoute", (float latStart, float lonStart, float latEnd, float lonEnd) =>
{
DateTime startCalc = DateTime.Now;
List<PathNode> result = Pathfinder.AStarTime("D:/stuttgart-regbez-latest", new Coordinates(latStart, lonStart), new Coordinates(latEnd, lonEnd), vehicle);
PathResult pathResult = new PathResult(DateTime.Now - startCalc, result);
return pathResult;
}
Pathfinder result = new Pathfinder("D:/stuttgart-regbez-latest", 0, 30).AStar(new Coordinates(latStart, lonStart),
new Coordinates(latEnd, lonEnd), Tag.SpeedType.any, 3);
return result.pathResult;
}
);
app.MapGet("/getClosestNode", (float lat, float lon) =>
@ -54,21 +50,3 @@ app.MapControllers();
app.Run();
internal class PathResult
{
[JsonInclude]public TimeSpan calcTime;
[JsonInclude] public double pathWeight = double.MaxValue;
[JsonInclude] public double pathTravelDistance = double.MaxValue;
[JsonInclude]public List<PathNode> pathNodes;
public PathResult(TimeSpan calcTime, List<PathNode> pathNodes)
{
this.calcTime = calcTime;
this.pathNodes = pathNodes;
if (pathNodes.Count > 0)
{
this.pathWeight = pathNodes.Last().currentPathWeight;
this.pathTravelDistance = pathNodes.Last().currentPathLength;
}
}
}

View File

@ -21,8 +21,7 @@ public class Coordinates
if (obj == null || obj.GetType() != this.GetType())
return false;
Coordinates convObj = (Coordinates)obj;
// ReSharper disable twice CompareOfFloatsByEqualityOperator static values
return convObj.latitude == this.latitude && convObj.longitude == this.longitude;
return convObj.latitude.Equals(this.latitude) && convObj.longitude.Equals(longitude);
}
public static ulong GetRegionHashCode(float latitude, float longitude)
@ -49,6 +48,6 @@ public class Coordinates
public override string ToString()
{
return
$"lat:{latitude.ToString(NumberFormatInfo.InvariantInfo)} lon:{longitude.ToString(CultureInfo.InvariantCulture)}";
$"Coordinates lat:{latitude.ToString(NumberFormatInfo.InvariantInfo)} lon:{longitude.ToString(CultureInfo.InvariantCulture)}";
}
}

View File

@ -22,6 +22,6 @@ public class OsmEdge
public override string ToString()
{
return $"w:{wayId} n1:{startId} n2:{neighborId} in r:{neighborRegion}";
return $"Edge wayId:{wayId} n1:{startId} n2:{neighborId} in regionId:{neighborRegion}";
}
}

View File

@ -1,4 +1,3 @@
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace OSMDatastructure.Graph;
@ -8,33 +7,20 @@ public class OsmNode
{
public ulong nodeId { get; }
public HashSet<OsmEdge> edges { get; set; }
public Coordinates coordinates { get; }
[JsonIgnore][NonSerialized]public OsmNode? previousPathNode = null;
[JsonIgnore][NonSerialized]public double currentPathWeight = double.MaxValue;
[JsonIgnore][NonSerialized]public double currentPathLength = double.MaxValue;
[JsonIgnore][NonSerialized]public double directDistanceToGoal = double.MaxValue;
public Coordinates coordinates { get; }
[OnDeserialized]
internal void SetDefaultValues(StreamingContext context)
{
currentPathWeight = double.MaxValue;
currentPathLength = double.MaxValue;
directDistanceToGoal = double.MaxValue;
}
public OsmNode(ulong nodeId, float lat, float lon)
{
this.nodeId = nodeId;
this.edges = new();
this.coordinates = new Coordinates(lat, lon);
edges = new();
coordinates = new Coordinates(lat, lon);
}
[JsonConstructor]
public OsmNode(ulong nodeId, Coordinates coordinates)
{
this.nodeId = nodeId;
this.edges = new();
edges = new();
this.coordinates = coordinates;
}
@ -43,7 +29,8 @@ public class OsmNode
HashSet<OsmEdge> e = edges.Where(edge => edge.neighborId == n.nodeId).ToHashSet();
if (e.Count > 0)
return e.First();
else return null;
return null;
}
public override bool Equals(object? obj)
@ -53,9 +40,6 @@ public class OsmNode
public override string ToString()
{
if(previousPathNode is not null)
return $"{nodeId} {coordinates} ec:{edges.Count} d:{directDistanceToGoal} w:{currentPathWeight} l:{currentPathLength} p:{previousPathNode.nodeId}";
return
$"{nodeId} {coordinates} ec:{edges.Count} d:{directDistanceToGoal} w:{currentPathWeight} l:{currentPathLength} null";
return $"Node id:{nodeId} coordinates:{coordinates} edges-count:{edges.Count}";
}
}

View File

@ -47,16 +47,12 @@ public class Region
public OsmNode? GetNode(ulong id)
{
if (ContainsNode(id))
return nodes.First(node => node.nodeId == id);
else return null;
return ContainsNode(id) ? nodes.First(node => node.nodeId == id) : null;
}
public OsmNode? GetNode(Coordinates coordinates)
{
if (ContainsNode(coordinates))
return nodes.First(node => node.coordinates.Equals(coordinates));
else return null;
return ContainsNode(coordinates) ? nodes.First(node => node.coordinates.Equals(coordinates)) : null;
}
}

View File

@ -18,7 +18,7 @@ public class Tag
switch (key)
{
case TagType.highway:
this.value = (WayType)value.GetByte();
this.value = value.GetByte();
break;
case TagType.maxspeed:
this.value = value.GetByte();
@ -30,6 +30,10 @@ public class Tag
case TagType.id:
this.value = value.GetUInt64();
break;
case TagType.name:
case TagType.tagref:
this.value = value.GetString();
break;
default:
this.value = value;
break;
@ -41,49 +45,59 @@ public class Tag
}
}
public static Tag? ConvertToTag(string key, string value)
public static HashSet<Tag> ConvertToTags(string key, string value)
{
HashSet<Tag> ret = new HashSet<Tag>();
switch (key)
{
case "highway":
try
{
return new Tag(TagType.highway, (WayType)Enum.Parse(typeof(WayType), value, true));
ret.Add(new Tag(TagType.highway, (WayType)Enum.Parse(typeof(WayType), value, true)));
}
catch (ArgumentException)
{
return new Tag(TagType.highway, WayType.unclassified);
ret.Add(new Tag(TagType.highway, WayType.unclassified));
}
break;
case "maxspeed":
case "maxspeed:max":
try
{
byte speed = Convert.ToByte(value);
if (speed == 255)
return new Tag(TagType.highway, false);
else
return new Tag(TagType.maxspeed, speed);
if (speed != 255)
ret.Add(new Tag(TagType.maxspeed, speed));
}
catch (Exception)
{
//Console.WriteLine(e);
//Console.WriteLine("Continuing...");
return new Tag(TagType.maxspeed, byte.MaxValue);
ret.Add(new Tag(TagType.maxspeed, byte.MinValue));
}
break;
case "oneway":
switch (value)
{
case "yes":
return new Tag(TagType.oneway, true);
ret.Add(new Tag(TagType.oneway, true));
break;
case "-1":
return new Tag(TagType.forward, false);
ret.Add(new Tag(TagType.forward, false));
ret.Add(new Tag(TagType.oneway, true));
break;
case "no":
return new Tag(TagType.oneway, false);
ret.Add(new Tag(TagType.oneway, false));
break;
}
break;
case "name":
ret.Add(new Tag(TagType.name, value));
break;
case "ref":
ret.Add(new Tag(TagType.tagref, value));
break;
}
return null;
return ret;
}
public override string ToString()
@ -93,28 +107,28 @@ public class Tag
public enum TagType : byte
{
highway, oneway, footway, sidewalk, cycleway, busway, forward, maxspeed, name, surface, lanes, access, tracktype, id
highway, oneway, footway, sidewalk, cycleway, busway, forward, maxspeed, name, surface, lanes, access, tracktype, id, tagref
}
public static readonly Dictionary<WayType, byte> defaultSpeedCar = new() {
{ WayType.NONE, 0 },
{ WayType.motorway, 100 },
{ WayType.motorroad, 90 },
{ WayType.motorway, 130 },
{ WayType.motorroad, 100 },
{ WayType.trunk, 85 },
{ WayType.primary, 65 },
{ WayType.secondary, 60 },
{ WayType.tertiary, 50 },
{ WayType.unclassified, 15 },
{ WayType.residential, 10 },
{ WayType.unclassified, 30 },
{ WayType.residential, 20 },
{ WayType.motorway_link, 60 },
{ WayType.trunk_link, 50 },
{ WayType.primary_link, 50 },
{ WayType.secondary_link, 50 },
{ WayType.tertiary_link, 30 },
{ WayType.living_street, 10 },
{ WayType.service, 1 },
{ WayType.service, 0 },
{ WayType.pedestrian, 0 },
{ WayType.track, 15 },
{ WayType.track, 0 },
{ WayType.bus_guideway, 0 },
{ WayType.escape, 0 },
{ WayType.raceway, 0 },

View File

@ -1,5 +1,4 @@
using System.Text.Json.Serialization;
using OSMDatastructure.Graph;
namespace OSMDatastructure;
@ -25,9 +24,10 @@ public class TagManager
public void AddTag(ulong wayId, string key, string value)
{
Tag? tag = Tag.ConvertToTag(key, value);
if(tag is not null)
AddTag(wayId, tag);
HashSet<Tag> pTags = Tag.ConvertToTags(key, value);
if(pTags.Count > 0)
foreach (Tag pTag in pTags)
AddTag(wayId, pTag);
}
public void AddTag(ulong wayId, Tag tag)

View File

@ -65,12 +65,12 @@ namespace OSMDatastructure
return d;
}
private static double DegreesToRadians(double deg)
public static double DegreesToRadians(double deg)
{
return deg * Math.PI / 180.0;
}
private static double RadiansToDegrees(double rad)
public static double RadiansToDegrees(double rad)
{
return rad * 180.0 / Math.PI;
}

View File

@ -8,6 +8,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Pathfinding", "Pathfinding\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{1D364F40-1681-4D36-A625-83B324F6AC89}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RenderPath", "RenderPath\RenderPath.csproj", "{54CAC127-4EB6-4E06-A5C8-35343C5FF76A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -30,5 +32,9 @@ Global
{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
{54CAC127-4EB6-4E06-A5C8-35343C5FF76A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54CAC127-4EB6-4E06-A5C8-35343C5FF76A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54CAC127-4EB6-4E06-A5C8-35343C5FF76A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{54CAC127-4EB6-4E06-A5C8-35343C5FF76A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -6,13 +6,13 @@ namespace Pathfinding;
public class PathNode : OsmNode
{
[JsonInclude]public new double directDistanceToGoal = double.MaxValue;
[JsonInclude]public double directDistanceDelta = double.MaxValue;
[JsonInclude]public new double currentPathLength = double.MaxValue;
[JsonInclude]public double pathDistanceDelta = double.MaxValue;
[JsonInclude]public new double currentPathWeight = double.MaxValue;
[JsonInclude]public double pathWeightDelta = double.MaxValue;
[JsonInclude]public Dictionary<string, string> tags = new();
[JsonConstructor]
public PathNode(ulong nodeId, Coordinates coordinates, Dictionary<string, string> tags) : base(nodeId, coordinates)
{
this.tags = tags;
}
public PathNode(ulong nodeId, float lat, float lon) : base(nodeId, lat, lon)
{
@ -22,19 +22,11 @@ public class PathNode : OsmNode
{
}
public static PathNode? FromOsmNode(OsmNode? node, HashSet<Tag>? tags, double pathDistanceDelta, double pathWeightDelta, double directDistanceDelta)
public static PathNode? FromOsmNode(OsmNode? node, HashSet<Tag>? tags)
{
if (node is null)
return null;
PathNode retNode = new(node.nodeId, node.coordinates)
{
currentPathLength = node.currentPathLength,
currentPathWeight = double.IsPositiveInfinity(node.currentPathWeight) ? double.MaxValue : node.currentPathWeight,
directDistanceToGoal = node.directDistanceToGoal,
directDistanceDelta = directDistanceDelta,
pathDistanceDelta = pathDistanceDelta,
pathWeightDelta = pathWeightDelta
};
PathNode retNode = new(node.nodeId, node.coordinates);
if (tags != null)
foreach (Tag tag in tags)
{

27
Pathfinding/PathResult.cs Normal file
View File

@ -0,0 +1,27 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Pathfinding;
public class PathResult
{
[JsonInclude]public double distance;
[JsonInclude]public double weight;
[JsonInclude]public TimeSpan calcTime;
[JsonInclude]public List<PathNode> pathNodes;
[JsonConstructor]
public PathResult(TimeSpan calcTime, List<PathNode> pathNodes, double distance, double weight)
{
this.calcTime = calcTime;
this.pathNodes = pathNodes;
this.distance = distance;
this.weight = weight;
}
public static PathResult PathresultFromFile(string filePath)
{
return JsonSerializer.Deserialize<PathResult>(new FileStream(filePath, FileMode.Open, FileAccess.Read,
FileShare.Read))!;
}
}

View File

@ -1,166 +1,228 @@
using OSMDatastructure;
using System.Text.Json;
using OSMDatastructure;
using OSMDatastructure.Graph;
using WayType = OSMDatastructure.Tag.WayType;
using static OSMDatastructure.Tag;
namespace Pathfinding;
public static partial class Pathfinder
public class Pathfinder
{
private static ValueTuple<OsmNode?, OsmNode?> SetupNodes(Coordinates startCoordinates, Coordinates goalCoordinates, RegionManager regionManager )
public RegionManager regionManager;
public PathResult? pathResult;
public Dictionary<OsmNode, double>? gScore;
private Dictionary<OsmNode, OsmNode>? _cameFromDict;
private SpeedType _speedType;
private double roadPriorityFactor, turnAngle;
public Pathfinder(string workingDirectory, double roadPriorityFactor, double turnAngle)
{
ValueTuple<OsmNode?, OsmNode?> retTuple = new();
retTuple.Item1 = regionManager.ClosestNodeToCoordinates(startCoordinates, Tag.SpeedType.any);
retTuple.Item2 = regionManager.ClosestNodeToCoordinates(goalCoordinates, Tag.SpeedType.any);
if (retTuple.Item1 is null || retTuple.Item2 is null)
return retTuple;
retTuple.Item1.currentPathWeight = 0;
retTuple.Item1.currentPathLength = 0;
retTuple.Item1.directDistanceToGoal = Utils.DistanceBetween(retTuple.Item1, retTuple.Item2);
return retTuple;
if (!Path.Exists(workingDirectory))
throw new DirectoryNotFoundException(workingDirectory);
regionManager = new(workingDirectory);
this.roadPriorityFactor = roadPriorityFactor;
this.turnAngle = turnAngle;
}
private static double EdgeWeight(OsmNode node1, OsmEdge edge, Tag.SpeedType vehicle, RegionManager regionManager)
public Pathfinder(RegionManager regionManager, double roadPriorityFactor, double turnAngle)
{
OsmNode? node2 = regionManager.GetNode(edge.neighborId, edge.neighborRegion);
if (node2 is null)
return double.MaxValue;
double distance = Utils.DistanceBetween(node1, node2);
byte speed = regionManager.GetSpeedForEdge(node1, edge.wayId, vehicle);
return speed is 0 ? double.MaxValue : distance / speed;
this.regionManager = regionManager;
this.roadPriorityFactor = roadPriorityFactor;
this.turnAngle = turnAngle;
}
private static double GetPriority(OsmNode current, OsmNode? previous, OsmEdge edge, Tag.SpeedType vehicle, RegionManager regionManager)
public Pathfinder AStar(Coordinates startCoordinates, Coordinates goalCoordinates, SpeedType vehicle, double extraTime)
{
if (vehicle == Tag.SpeedType.any)
return 1;
const double roadPriorityFactor = 1;
const double junctionFactor = 2;
const double wayChangeFactor = 2;
Region r = regionManager.GetRegion(current.coordinates)!;
double roadPriority = GetPriorityVehicleRoad(edge, vehicle, r) * 0.1 * roadPriorityFactor;
double roadSpeed = regionManager.GetSpeedForEdge(current, edge.wayId, vehicle);
if(vehicle == Tag.SpeedType.pedestrian)
return (current.directDistanceToGoal / roadSpeed) * roadPriority;
ulong previousWayId = UInt64.MaxValue;
if (previous?.edges is not null)
DateTime startCalc = DateTime.Now;
_speedType = vehicle;
OsmNode? startNode = regionManager.ClosestNodeToCoordinates(startCoordinates, _speedType);
OsmNode? goalNode = regionManager.ClosestNodeToCoordinates(goalCoordinates, _speedType);
if (startNode is null || goalNode is null)
{
foreach (OsmEdge e in previous.edges)
if (e.neighborId.Equals(current.nodeId))
pathResult = new(DateTime.Now - startCalc, new List<PathNode>(),0 ,0);
return this;
}
RPriorityQueue<OsmNode, double> openSetfScore = new();
openSetfScore.Enqueue(startNode, 0);
gScore = new() { { startNode, 0 } };
_cameFromDict = new();
bool found = false;
bool stop = false;
TimeSpan firstFound = TimeSpan.MaxValue;
double maxGscore = double.MaxValue;
while (openSetfScore.Count > 0 && !stop)
{
OsmNode currentNode = openSetfScore.Dequeue()!;
if (currentNode.Equals(goalNode))
{
if (!found)
{
previousWayId = e.wayId;
break;
firstFound = DateTime.Now - startCalc;
found = true;
Console.WriteLine($"First: {firstFound} Multiplied by {extraTime}: {firstFound.Multiply(extraTime)}");
}
}
maxGscore = gScore[goalNode];
}
double junctionPriority = (current.edges.Count > 2 ? 1 : 0) * junctionFactor;
double wayChange = (previousWayId != edge.wayId ? 1 : 0) * wayChangeFactor;
if (found && DateTime.Now - startCalc > firstFound.Multiply(extraTime))
stop = true;
foreach (OsmEdge edge in currentNode.edges)
{
OsmNode? neighbor = regionManager.GetNode(edge.neighborId, edge.neighborRegion);
if (neighbor is not null)
{
double tentativeGScore = gScore[currentNode] + Weight(currentNode, neighbor, edge);
gScore.TryAdd(neighbor, double.MaxValue);
if ((!found || (found && tentativeGScore < maxGscore)) && tentativeGScore < gScore[neighbor])
{
if(!_cameFromDict.TryAdd(neighbor, currentNode))
_cameFromDict[neighbor] = currentNode;
gScore[neighbor] = tentativeGScore;
double h = Heuristic(currentNode, neighbor, goalNode, edge);
openSetfScore.Enqueue(neighbor, tentativeGScore + h);
}
}
}
}
if(vehicle == Tag.SpeedType.car)
return (current.directDistanceToGoal / roadSpeed) * roadPriority * ((junctionPriority + wayChange) / 2);
return double.MaxValue;
TimeSpan calcTime = DateTime.Now - startCalc;
if (!found)
{
pathResult = new(DateTime.Now - startCalc, new List<PathNode>(),0 ,0);
Console.Write("No path found.");
return this;
}
else
{
pathResult = GetPath(goalNode, calcTime);
}
Console.WriteLine($"Path found. {calcTime} PathLength {pathResult.pathNodes.Count} VisitedNodes {gScore.Count} Distance {pathResult.distance} Duration {pathResult.weight}");
return this;
}
private static double GetPriorityVehicleRoad(OsmEdge edge, Tag.SpeedType vehicle, Region region)
private double Weight(OsmNode currentNode, OsmNode neighborNode, OsmEdge edge)
{
if (vehicle == Tag.SpeedType.any)
return 1;
WayType? wayType = (WayType?)region.tagManager.GetTag(edge.wayId, Tag.TagType.highway);
if(wayType is null)
return double.MaxValue;
if (vehicle == Tag.SpeedType.car)
{
switch (wayType)
{
case WayType.motorway:
case WayType.motorway_link:
case WayType.motorroad:
case WayType.trunk:
case WayType.trunk_link:
case WayType.primary:
case WayType.primary_link:
return 1;
case WayType.secondary:
case WayType.secondary_link:
return 2;
case WayType.tertiary:
case WayType.tertiary_link:
return 3;
case WayType.unclassified:
case WayType.residential:
case WayType.road:
return 4;
case WayType.living_street:
case WayType.service:
case WayType.track:
return 5;
default:
return 100;
}
}
if (vehicle == Tag.SpeedType.pedestrian)
{
switch (wayType)
{
case WayType.pedestrian:
case WayType.corridor:
case WayType.footway:
case WayType.path:
case WayType.steps:
case WayType.residential:
case WayType.living_street:
return 1;
case WayType.service:
case WayType.cycleway:
case WayType.bridleway:
case WayType.road:
case WayType.track:
case WayType.unclassified:
return 2;
case WayType.tertiary:
case WayType.tertiary_link:
case WayType.escape:
return 5;
default:
return 100;
}
}
double distance = Utils.DistanceBetween(currentNode, neighborNode);
double speed = regionManager.GetSpeedForEdge(currentNode, edge.wayId, _speedType);
return 100;
double angle = 1;
if (_cameFromDict!.ContainsKey(currentNode))
{
OsmNode previousNode = _cameFromDict[currentNode];
Vector v1 = new(currentNode, previousNode);
Vector v2 = new(currentNode, neighborNode);
double nodeAngle = v1.Angle(v2);
if (nodeAngle < turnAngle)
angle = 0;
else
angle = nodeAngle / 180;
}
double prio = regionManager.GetPriorityForVehicle(_speedType,edge, currentNode) * roadPriorityFactor;
return distance / (speed * angle + prio + 1);
}
private static List<PathNode> GetRouteFromCalc(OsmNode goalNode, RegionManager regionManager)
private double Heuristic(OsmNode currentNode, OsmNode neighborNode, OsmNode goalNode, OsmEdge edge)
{
if (neighborNode.Equals(goalNode)) return 0;
double priority = regionManager.GetPriorityForVehicle(_speedType, edge, currentNode);
if (priority == 0)
return double.MaxValue;
double distance = Utils.DistanceBetween(neighborNode, goalNode);
double speed = regionManager.GetSpeedForEdge(currentNode, edge.wayId, _speedType);
double roadPriority = priority * roadPriorityFactor;
double angle = 0;
if (_cameFromDict!.ContainsKey(currentNode))
{
OsmNode previousNode = _cameFromDict[currentNode];
Vector v1 = new(currentNode, previousNode);
Vector v2 = new(currentNode, neighborNode);
double nodeAngle = v1.Angle(v2);
if (nodeAngle < turnAngle)
angle = 0;
else
angle = nodeAngle / 180;
}
return distance / (speed * angle + roadPriority + 1);
}
public void SaveResult(string path)
{
if(File.Exists(path))
File.Delete(path);
FileStream fs = new (path, FileMode.CreateNew);
JsonSerializer.Serialize(fs, pathResult, JsonSerializerOptions.Default);
fs.Dispose();
Console.WriteLine($"Saved result to {path}");
}
private PathResult GetPath(OsmNode goalNode, TimeSpan calcFinished)
{
List<PathNode> path = new();
OsmNode? currentNode = goalNode;
while (currentNode is not null)
OsmNode currentNode = goalNode;
double retDistance = 0;
double weight = 0;
while (_cameFromDict!.ContainsKey(_cameFromDict[currentNode]))
{
HashSet<Tag>? tags = null;
double pathDistanceDelta = 0;
double pathWeightDelta = 0;
double directDistanceDelta = 0;
if (currentNode.previousPathNode is not null)
{
OsmEdge edge = currentNode.previousPathNode!.edges.First(e => e.neighborId.Equals(currentNode.nodeId));
tags = regionManager.GetRegion(currentNode.coordinates)!.tagManager.GetTagsForWayId(edge.wayId);
pathDistanceDelta = currentNode.currentPathLength - currentNode.previousPathNode.currentPathLength;
pathWeightDelta = currentNode.currentPathWeight - currentNode.previousPathNode.currentPathWeight;
directDistanceDelta =
currentNode.directDistanceToGoal - currentNode.previousPathNode.directDistanceToGoal;
}
OsmEdge? currentEdge = _cameFromDict[currentNode].edges.FirstOrDefault(edge => edge.neighborId == currentNode.nodeId);
HashSet<Tag>? tags =
regionManager.GetRegion(currentNode.coordinates)!.tagManager.GetTagsForWayId(currentEdge!.wayId);
PathNode? newNode = PathNode.FromOsmNode(currentNode, tags);
if(newNode is not null)
path.Add(newNode);
PathNode? pn = PathNode.FromOsmNode(currentNode, tags, pathDistanceDelta, pathWeightDelta, directDistanceDelta);
if(pn is not null)
path.Add(pn!);
currentNode = currentNode.previousPathNode;
double distance = Utils.DistanceBetween(currentNode, _cameFromDict[currentNode]);
retDistance += distance;
weight += regionManager.GetSpeedForEdge(_cameFromDict[currentNode], currentEdge.wayId, _speedType);
currentNode = _cameFromDict[currentNode];
}
path.Reverse();
return path;
return new PathResult(calcFinished, path, retDistance, retDistance / (weight / path.Count));
}
private class Vector
{
public readonly float x, y;
public Vector(float x, float y)
{
this.x = x;
this.y = y;
}
public Vector(OsmNode n1, OsmNode n2)
{
this.x = n1.coordinates.longitude - n2.coordinates.longitude;
this.y = n1.coordinates.latitude - n2.coordinates.latitude;
}
public double Angle(Vector v2)
{
return Angle(this, v2);
}
public static double Angle(Vector v1, Vector v2)
{
double dotProd = v1.x * v2.x + v1.y * v2.y;
double v1L = Math.Sqrt(v1.x * v1.x + v1.y * v1.y);
double v2L = Math.Sqrt(v2.x * v2.x + v2.y * v2.y);
double ang = Math.Acos(dotProd / (v1L * v2L));
if (ang.Equals(double.NaN))
return 0;
double angle = Utils.RadiansToDegrees(ang);
return angle;
}
}
}

View File

@ -1,51 +0,0 @@
using OSMDatastructure;
using OSMDatastructure.Graph;
namespace Pathfinding;
public static partial class Pathfinder
{
public static List<PathNode> AStarDistance(string workingDir, Coordinates start,
Coordinates goal)
{
RegionManager regionManager = new (workingDir);
ValueTuple<OsmNode?, OsmNode?> startAndEndNode = SetupNodes(start, goal, regionManager);
if (startAndEndNode.Item1 is null || startAndEndNode.Item2 is null)
return new List<PathNode>();
OsmNode goalNode = startAndEndNode.Item2!;
PriorityQueue<OsmNode, double> toVisit = new();
toVisit.Enqueue(startAndEndNode.Item1, 0);
bool stop = false;
while (toVisit.Count > 0)
{
OsmNode currentNode = toVisit.Dequeue();
foreach (OsmEdge edge in currentNode.edges)
{
OsmNode? neighbor = regionManager.GetNode(edge.neighborId, edge.neighborRegion);
if (neighbor is not null)
{
if (Math.Abs(neighbor.directDistanceToGoal - double.MaxValue) < 1)
neighbor.directDistanceToGoal = Utils.DistanceBetween(neighbor, goalNode);
double newPotentialLength = currentNode.currentPathLength + Utils.DistanceBetween(currentNode, neighbor);
if (newPotentialLength < neighbor.currentPathLength)
{
neighbor.previousPathNode = currentNode;
neighbor.currentPathLength = newPotentialLength;
if(neighbor.Equals(goalNode))
return GetRouteFromCalc(goalNode, regionManager);
//stop = true;
if (!toVisit.UnorderedItems.Any(item => item.Element.Equals(neighbor)) && !stop)
{
toVisit.Enqueue(neighbor, neighbor.directDistanceToGoal);
}
}
}
}
}
return GetRouteFromCalc(goalNode, regionManager);
}
}

View File

@ -1,65 +0,0 @@
using OSMDatastructure;
using OSMDatastructure.Graph;
using Utils = OSMDatastructure.Utils;
namespace Pathfinding;
public static partial class Pathfinder
{
public static List<PathNode> AStarTime(string workingDir, Coordinates start,
Coordinates goal, Tag.SpeedType vehicle)
{
RegionManager regionManager = new (workingDir);
ValueTuple<OsmNode?, OsmNode?> startAndEndNode = SetupNodes(start, goal, regionManager);
if (startAndEndNode.Item1 is null || startAndEndNode.Item2 is null)
return new List<PathNode>();
OsmNode goalNode = startAndEndNode.Item2!;
PriorityQueue<OsmNode, double> toVisit = new();
toVisit.Enqueue(startAndEndNode.Item1, 0);
bool stop = false;
while (toVisit.Count > 0)
{
OsmNode currentNode = toVisit.Dequeue();
foreach (OsmEdge edge in currentNode.edges.Where(
edge => regionManager.TestValidConnectionForType(currentNode, edge, vehicle)))
{
OsmNode? neighbor = regionManager.GetNode(edge.neighborId, edge.neighborRegion);
if (neighbor is not null)
{
if (Math.Abs(neighbor.directDistanceToGoal - double.MaxValue) < 1)
neighbor.directDistanceToGoal = Utils.DistanceBetween(neighbor, goalNode);
double newPotentialWeight = currentNode.currentPathWeight +
EdgeWeight(currentNode, edge, vehicle, regionManager);
if (newPotentialWeight < neighbor.currentPathWeight)
{
neighbor.previousPathNode = currentNode;
neighbor.currentPathWeight = newPotentialWeight;
if (neighbor.Equals(goalNode))
{
currentNode = neighbor;
currentNode.currentPathLength = 0;
while (currentNode != startAndEndNode.Item1 && currentNode.previousPathNode is not null)
{
currentNode.previousPathNode.currentPathLength = currentNode.currentPathLength +
Utils.DistanceBetween(currentNode, currentNode.previousPathNode);
currentNode = currentNode.previousPathNode;
}
return GetRouteFromCalc(goalNode, regionManager);
}
//stop = true;
if (!toVisit.UnorderedItems.Any(item => item.Element.Equals(neighbor)))
toVisit.Enqueue(neighbor, GetPriority(currentNode, currentNode.previousPathNode, edge, vehicle, regionManager));
}
}
}
}
return GetRouteFromCalc(goalNode, regionManager);
}
}

View File

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

View File

@ -0,0 +1,47 @@
namespace Pathfinding;
public class RPriorityQueue<TKey, TPriority> where TKey : notnull
{
public Dictionary<TKey, TPriority> queue;
public int Count => queue.Count;
public RPriorityQueue()
{
queue = new();
}
public void Enqueue(TKey key, TPriority priority)
{
if (!queue.TryAdd(key, priority))
queue[key] = priority;
}
public TKey Dequeue()
{
TKey retKey = queue.MinBy(item => item.Value).Key;
queue.Remove(retKey);
return retKey;
}
public int Remove(IEnumerable<TKey> elements)
{
int before = Count;
queue = queue.Where(queueitem => !elements.Contains(queueitem.Key))
.ToDictionary(item => item.Key, item => item.Value);
return before - Count;
}
public int RemoveExcept(IEnumerable<TKey> exceptKeys)
{
int before = Count;
queue = queue.IntersectBy(exceptKeys, item => item.Key).ToDictionary(item => item.Key, item => item.Value);
return before - Count;
}
public int Clear()
{
int before = Count;
queue.Clear();
return before;
}
}

View File

@ -1,6 +1,8 @@
using System.Text.Json;
using OSMDatastructure;
using OSMDatastructure.Graph;
using SpeedType = OSMDatastructure.Tag.SpeedType;
using WayType = OSMDatastructure.Tag.WayType;
namespace Pathfinding
{
@ -21,31 +23,32 @@ namespace Pathfinding
public Region? GetRegion(ulong id)
{
if(_regions.TryGetValue(id, out Region? value))
return value;
else
if (!_regions.ContainsKey(id))
{
Region? loadedRegion = RegionFromId(id);
if(loadedRegion is not null)
_regions.Add(loadedRegion!.regionHash, value: loadedRegion);
return loadedRegion;
if (loadedRegion is not null)
_regions.TryAdd(loadedRegion.regionHash, loadedRegion);
return _regions[id]; //return from _regions instead of loadedRegion for multithreading/pointers
}
return _regions[id];
}
public Region[] GetAllRegions()
{
return this._regions.Values.ToArray();
return _regions.Values.ToArray();
}
private Region? RegionFromFile(string filePath)
private static Region? RegionFromFile(string filePath)
{
Region? retRegion = null;
if (File.Exists(filePath))
if (!File.Exists(filePath))
{
FileStream regionFile = new FileStream(filePath, FileMode.Open);
retRegion = JsonSerializer.Deserialize<Region>(regionFile, Region.serializerOptions)!;
regionFile.Dispose();
//throw new FileNotFoundException(filePath);
return null;
}
FileStream regionFile = new (filePath, FileMode.Open, FileAccess.Read, FileShare.Read, (int)new FileInfo(filePath).Length, FileOptions.SequentialScan);
Region retRegion = JsonSerializer.Deserialize<Region>(regionFile, Region.serializerOptions)!;
regionFile.Dispose();
return retRegion;
}
@ -61,26 +64,25 @@ namespace Pathfinding
return r?.GetNode(nodeId);
}
public bool TestValidConnectionForType(OsmNode node1, OsmNode node2, Tag.SpeedType type)
public bool TestValidConnectionForType(OsmNode node1, OsmNode node2, SpeedType type)
{
foreach (OsmEdge edge in node1.edges)
foreach (OsmEdge edge in node1.edges.Where(edge => edge.neighborId.Equals(node2.nodeId)))
{
if (edge.neighborId.Equals(node2.nodeId))
return TestValidConnectionForType(node1, edge, type);
return TestValidConnectionForType(node1, edge, type);
}
return false;
}
public bool TestValidConnectionForType(OsmNode node1, OsmEdge edge, Tag.SpeedType type)
public bool TestValidConnectionForType(OsmNode node1, OsmEdge edge, SpeedType type)
{
if (type == Tag.SpeedType.any)
if (type == SpeedType.any)
return true;
byte speed = GetSpeedForEdge(node1, edge.wayId, type);
return (speed is not 0);
}
public OsmNode? ClosestNodeToCoordinates(Coordinates coordinates, Tag.SpeedType vehicle)
public OsmNode? ClosestNodeToCoordinates(Coordinates coordinates, SpeedType vehicle)
{
OsmNode? closest = null;
double distance = double.MaxValue;
@ -90,19 +92,18 @@ namespace Pathfinding
foreach (OsmNode node in region.nodes)
{
bool hasConnectionUsingVehicle = true;
if (vehicle is not Tag.SpeedType.any)
if (vehicle is not SpeedType.any)
{
hasConnectionUsingVehicle = false;
foreach (OsmEdge edge in node.edges)
{
byte speed = GetSpeedForEdge(node, edge.wayId, vehicle);
if (speed != 0)
if (TestValidConnectionForType(node, edge, vehicle))
hasConnectionUsingVehicle = true;
}
}
double nodeDistance = Utils.DistanceBetween(node, coordinates);
if (nodeDistance < distance && hasConnectionUsingVehicle)
if (hasConnectionUsingVehicle && nodeDistance < distance)
{
closest = node;
distance = nodeDistance;
@ -112,25 +113,88 @@ namespace Pathfinding
return closest;
}
public byte GetSpeedForEdge(OsmNode node1, ulong wayId, Tag.SpeedType vehicle)
public byte GetSpeedForEdge(OsmNode node1, ulong wayId, SpeedType vehicle)
{
TagManager tags = GetRegion(node1.coordinates)!.tagManager;
Tag.WayType wayType = (Tag.WayType)tags.GetTag(wayId, Tag.TagType.highway)!;
WayType wayType = (WayType)tags.GetTag(wayId, Tag.TagType.highway)!;
byte speed = 0;
switch (vehicle)
{
case Tag.SpeedType.pedestrian:
case SpeedType.pedestrian:
speed = Tag.defaultSpeedPedestrian[wayType];
return speed is not 0 ? speed : (byte)0;
case Tag.SpeedType.car:
return speed;
case SpeedType.car:
byte? maxSpeed = (byte?)tags.GetTag(wayId, Tag.TagType.maxspeed);
speed = Tag.defaultSpeedCar[wayType];
return maxSpeed < speed ? (byte)maxSpeed : speed;
case Tag.SpeedType.any:
case SpeedType.any:
return 1;
default:
return 0;
}
}
public double GetPriorityForVehicle(SpeedType speedType, OsmEdge edge, OsmNode node)
{
if (speedType == SpeedType.any)
return 1;
Region region = GetRegion(node.coordinates)!;
WayType? wayType = (WayType?)region.tagManager.GetTag(edge.wayId, Tag.TagType.highway);
if(wayType is null)
return 0;
if (speedType == SpeedType.car)
{
switch (wayType)
{
case WayType.motorway:
case WayType.motorway_link:
case WayType.motorroad:
return 20;
case WayType.trunk:
case WayType.trunk_link:
case WayType.primary:
case WayType.primary_link:
return 10;
case WayType.secondary:
case WayType.secondary_link:
case WayType.tertiary:
case WayType.tertiary_link:
return 6;
case WayType.unclassified:
case WayType.residential:
case WayType.road:
case WayType.living_street:
return 2;
}
}
if (speedType == SpeedType.pedestrian)
{
switch (wayType)
{
case WayType.pedestrian:
case WayType.corridor:
case WayType.footway:
case WayType.path:
case WayType.steps:
case WayType.residential:
case WayType.living_street:
return 10;
case WayType.service:
case WayType.cycleway:
case WayType.bridleway:
case WayType.road:
case WayType.track:
case WayType.unclassified:
return 5;
case WayType.tertiary:
case WayType.tertiary_link:
case WayType.escape:
return 2;
}
}
return 0;
}
}
}

33
RenderPath/Bounds.cs Normal file
View File

@ -0,0 +1,33 @@
using System.Text.Json.Serialization;
using OSMDatastructure.Graph;
namespace RenderPath;
public class Bounds
{
[JsonInclude]public float minLat, maxLat, minLon, maxLon;
[JsonConstructor]
public Bounds(float minLat, float minLon, float maxLat, float maxLon)
{
this.minLon = minLon;
this.maxLat = maxLat;
this.maxLon = maxLon;
this.minLat = minLat;
}
public static Bounds FromCoords(float lat1, float lon1, float lat2, float lon2)
{
float minLat = lat1 < lat2 ? lat1 : lat2;
float minLon = lon1 < lon2 ? lon1 : lon2;
float maxLat = lat1 > lat2 ? lat1 : lat2;
float maxLon = lon1 > lon2 ? lon1 : lon2;
return new Bounds(minLat, minLon, maxLat, maxLon);
}
public static Bounds FromCoords(Coordinates c1, Coordinates c2)
{
return FromCoords(c1.latitude, c1.longitude, c2.latitude, c2.longitude);
}
}

44
RenderPath/PNGRenderer.cs Normal file
View File

@ -0,0 +1,44 @@
using System.Drawing;
using System.Drawing.Imaging;
namespace RenderPath;
#pragma warning disable CA1416
public class PNGRenderer : Renderer
{
private readonly Image _image;
private readonly Graphics _graphics;
public PNGRenderer(int width, int height)
{
_image = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
_graphics = Graphics.FromImage(_image);
_graphics.Clear(Color.White);
}
public PNGRenderer(Image renderOver)
{
_image = renderOver;
_graphics = Graphics.FromImage(renderOver);
}
public override void DrawLine(float x1, float y1, float x2, float y2, int width, Color color)
{
Pen p = new Pen(color, width);
_graphics.DrawLine(p, x1, y1, x2, y2);
}
public override void DrawDot(float x, float y, int radius, Color color)
{
Brush b = new SolidBrush(color);
x -= radius / 2f;
y -= radius / 2f;
_graphics.FillEllipse(b, x, y, radius, radius);
}
public override void Save(string path)
{
_image.Save($"{path}.png", ImageFormat.Png);
}
}
#pragma warning restore CA1416

View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
<PackageReference Include="System.Runtime.Serialization.Json" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OSMDatastructure\OSMDatastructure.csproj" />
<ProjectReference Include="..\Pathfinding\Pathfinding.csproj" />
</ItemGroup>
</Project>

194
RenderPath/Renderer.cs Normal file
View File

@ -0,0 +1,194 @@
using System.Drawing;
using OSMDatastructure;
using OSMDatastructure.Graph;
using Pathfinding;
namespace RenderPath;
public abstract class Renderer
{
private const int ImageMaxSize = 20000;
private const int PenThickness = 2;
private static readonly Color RouteColor = Color.Red;
private static readonly Color WeightStartColor = Color.FromArgb(127, 0, 100, 255);
private static readonly Color WeightEndColor = Color.FromArgb(255, 0, 255, 0);
private static readonly Color RoadPrioStart = Color.FromArgb(200, 100, 100, 100);
private static readonly Color RoadPrioEnd = Color.FromArgb(255, 255, 180, 0);
public Bounds? bounds;
public enum RenderType { png, svg}
public abstract void DrawLine(float x1, float y1, float x2, float y2, int width, Color color);
public abstract void DrawDot(float x, float y, int r, Color color);
public abstract void Save(string path);
public static Renderer DrawArea(RegionManager rm, RenderType renderType)
{
HashSet<OsmNode> nodes = new();
foreach (OSMDatastructure.Region r in rm.GetAllRegions())
nodes = nodes.Concat(r.nodes).ToHashSet();
float minLat = nodes.Min(node => node.coordinates.latitude);
float minLon = nodes.Min(node => node.coordinates.longitude);
float maxLat = nodes.Max(node => node.coordinates.latitude);
float maxLon = nodes.Max(node => node.coordinates.longitude);
float latDiff = maxLat - minLat;
float lonDiff = maxLon - minLon;
float scaleFactor = latDiff > lonDiff ? ImageMaxSize / latDiff : ImageMaxSize / lonDiff;
int pixelsX = (int)(lonDiff * scaleFactor);
int pixelsY = (int)(latDiff * scaleFactor);
Renderer renderer;
switch (renderType)
{
case RenderType.svg:
renderer = new SVGRenderer(pixelsX, pixelsY);
break;
default:
renderer = new PNGRenderer(pixelsX, pixelsY);
break;
}
foreach (OsmNode node in nodes)
{
foreach (OsmEdge edge in node.edges)
{
double priority = rm.GetPriorityForVehicle(Tag.SpeedType.car, edge, node) / 20;
Coordinates c1 = node.coordinates;
OsmNode nNode = rm.GetNode(edge.neighborId, edge.neighborRegion)!;
Coordinates c2 = nNode.coordinates;
float x1 = (c1.longitude - minLon) * scaleFactor;
float y1 = (maxLat - c1.latitude) * scaleFactor;
float x2 = (c2.longitude - minLon) * scaleFactor;
float y2 = (maxLat - c2.latitude) * scaleFactor;
renderer.DrawLine(x1, y1, x2, y2, PenThickness, ColorInterp(RoadPrioStart, RoadPrioEnd, priority));
}
}
renderer.bounds = new Bounds(minLat,minLon,maxLat,maxLon);
return renderer;
}
public static Renderer DrawPath(PathResult pathResult, RenderType renderType, Renderer? drawOver)
{
List<Coordinates> coordinates = new();
foreach(PathNode node in pathResult.pathNodes)
coordinates.Add(node.coordinates);
float minLat = drawOver?.bounds!.minLat ?? coordinates.Min(coords => coords.latitude);
float minLon = drawOver?.bounds!.minLon ?? coordinates.Min(coords => coords.longitude);
float maxLat = drawOver?.bounds!.maxLat ?? coordinates.Max(coords => coords.latitude);
float maxLon = drawOver?.bounds!.maxLon ?? coordinates.Max(coords => coords.longitude);
float latDiff = maxLat - minLat;
float lonDiff = maxLon - minLon;
float scaleFactor = latDiff > lonDiff ? ImageMaxSize / latDiff : ImageMaxSize / lonDiff;
int pixelsX = (int)(lonDiff * scaleFactor);
int pixelsY = (int)(latDiff * scaleFactor);
Renderer renderer;
if(drawOver is null)
switch (renderType)
{
case RenderType.svg:
renderer = new SVGRenderer(pixelsX, pixelsY);
break;
default:
renderer = new PNGRenderer(pixelsX, pixelsY);
break;
}
else
renderer = drawOver;
for (int i = 0; i < coordinates.Count - 1; i++)
{
Coordinates c1 = coordinates[i];
Coordinates c2 = coordinates[i + 1];
float x1 = (c1.longitude - minLon) * scaleFactor;
float y1 = (maxLat - c1.latitude) * scaleFactor;
float x2 = (c2.longitude - minLon) * scaleFactor;
float y2 = (maxLat - c2.latitude) * scaleFactor;
renderer.DrawLine(x1, y1, x2, y2, PenThickness, RouteColor);
}
renderer.bounds = new Bounds(minLat, minLon, maxLat, maxLon);
return renderer;
}
public static Renderer DrawGScores(Dictionary<OsmNode, double> gScore, RenderType renderType, Renderer? drawOver)
{
float minLat = drawOver?.bounds!.minLat ?? gScore.Min(kv => kv.Key.coordinates.latitude);
float minLon = drawOver?.bounds!.minLon ?? gScore.Min(kv => kv.Key.coordinates.longitude);
float maxLat = drawOver?.bounds!.maxLat ?? gScore.Max(kv => kv.Key.coordinates.latitude);
float maxLon = drawOver?.bounds!.maxLon ?? gScore.Max(kv => kv.Key.coordinates.longitude);
double minWeight = gScore.Min(kv => kv.Value);
double maxWeight = gScore.Max(kv => kv.Value);
float latDiff = maxLat - minLat;
float lonDiff = maxLon - minLon;
float scaleFactor = latDiff > lonDiff ? ImageMaxSize / latDiff : ImageMaxSize / lonDiff;
int pixelsX = (int)(lonDiff * scaleFactor);
int pixelsY = (int)(latDiff * scaleFactor);
Renderer renderer;
if(drawOver is null)
switch (renderType)
{
case RenderType.svg:
renderer = new SVGRenderer(pixelsX, pixelsY);
break;
default:
renderer = new PNGRenderer(pixelsX, pixelsY);
break;
}
else
renderer = drawOver;
foreach (KeyValuePair<OsmNode, double> kv in gScore)
{
double percentage = (kv.Value - minWeight) / (maxWeight - minWeight);
float x = (kv.Key.coordinates.longitude - minLon) * scaleFactor;
float y = (maxLat - kv.Key.coordinates.latitude) * scaleFactor;
renderer.DrawDot(x, y, PenThickness, ColorInterp(WeightStartColor, WeightEndColor, percentage));
}
renderer.bounds = new Bounds(minLat,minLon,maxLat,maxLon);
return renderer;
}
public static Renderer DrawPathfinder(Pathfinder pathfinder, RenderType renderType)
{
Console.WriteLine("Rendering loaded Regions");
Renderer areaRender = DrawArea(pathfinder.regionManager, renderType);
Console.WriteLine("Rendering gScores (Weights)");
Renderer areaGScoreRender = DrawGScores(pathfinder.gScore!, renderType, areaRender);
Console.WriteLine("Rendering path");
Renderer areaGScorePathRender = DrawPath(pathfinder.pathResult!, renderType, areaGScoreRender);
return areaGScorePathRender;
}
/*
* https://stackoverflow.com/questions/55601338/get-a-color-value-within-a-gradient-based-on-a-value
*/
private static int LinearInterp(int start, int end, double percentage) => start + (int)Math.Round(percentage * (end - start));
private static Color ColorInterp(Color start, Color end, double percentage) =>
Color.FromArgb(LinearInterp(start.A, end.A, percentage),
LinearInterp(start.R, end.R, percentage),
LinearInterp(start.G, end.G, percentage),
LinearInterp(start.B, end.B, percentage));
}

92
RenderPath/SVGRenderer.cs Normal file
View File

@ -0,0 +1,92 @@
using System.Drawing;
namespace RenderPath;
using System.Xml;
public class SVGRenderer : Renderer
{
private readonly XmlDocument _image;
private XmlElement _document;
public SVGRenderer(int width, int height)
{
_image = new XmlDocument();
CreateTree(width, height);
}
public SVGRenderer(XmlDocument renderOver)
{
_image = renderOver;
_document = _image.GetElementById("svg")!;
}
private void CreateTree(int width, int height)
{
XmlDeclaration xmlDeclaration = _image.CreateXmlDeclaration( "1.0", "UTF-8", null );
_image.InsertBefore(xmlDeclaration, _image.DocumentElement);
XmlElement pElement = _image.CreateElement("svg");
XmlAttribute xmlns = _image.CreateAttribute("xmlns");
xmlns.Value = "http://www.w3.org/2000/svg";
pElement.Attributes.Append(xmlns);
XmlAttribute aWidth = _image.CreateAttribute("width");
aWidth.Value = width.ToString();
pElement.Attributes.Append(aWidth);
XmlAttribute aHeight = _image.CreateAttribute("height");
aHeight.Value = height.ToString();
pElement.Attributes.Append(aHeight);
_image.AppendChild(pElement);
_document = pElement;
}
public override void DrawLine(float x1, float y1, float x2, float y2, int width, Color color)
{
XmlElement newLine = _image.CreateElement("line");
XmlAttribute aX1 = _image.CreateAttribute("x1");
aX1.Value = Math.Floor(x1).ToString("0");
newLine.Attributes.Append(aX1);
XmlAttribute aY1 = _image.CreateAttribute("y1");
aY1.Value = Math.Floor(y1).ToString("0");
newLine.Attributes.Append(aY1);
XmlAttribute aX2 = _image.CreateAttribute("x2");
aX2.Value = Math.Floor(x2).ToString("0");
newLine.Attributes.Append(aX2);
XmlAttribute aY2 = _image.CreateAttribute("y2");
aY2.Value = Math.Floor(y2).ToString("0");
newLine.Attributes.Append(aY2);
XmlAttribute stroke = _image.CreateAttribute("stroke-width");
stroke.Value = width.ToString();
newLine.Attributes.Append(stroke);
XmlAttribute aColor = _image.CreateAttribute("stroke");
aColor.Value = HexFromColor(color);
newLine.Attributes.Append(aColor);
_document.AppendChild(newLine);
}
public override void DrawDot(float x, float y, int radius, Color color)
{
XmlElement newCircle = _image.CreateElement("circle");
XmlAttribute aX = _image.CreateAttribute("cx");
aX.Value = Math.Floor(x).ToString("0");
newCircle.Attributes.Append(aX);
XmlAttribute aY = _image.CreateAttribute("cy");
aY.Value = Math.Floor(y).ToString("0");
newCircle.Attributes.Append(aY);
XmlAttribute aR = _image.CreateAttribute("r");
aR.Value = radius.ToString();
newCircle.Attributes.Append(aR);
XmlAttribute fill = _image.CreateAttribute("fill");
fill.Value = HexFromColor(color);
newCircle.Attributes.Append(fill);
_document.AppendChild(newCircle);
}
public override void Save(string path)
{
_image.Save($"{path}.svg");
}
private static string HexFromColor(Color color)
{
return $"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
}

View File

@ -1,4 +1,3 @@
using System.Globalization;
using System.Text;
namespace Server;

View File

@ -129,9 +129,10 @@ public class RegionConverter
currentTags.TryAdd(Tag.TagType.id, Convert.ToUInt64(wayReader.GetAttribute("id")!));
if (wayReader.Name == "tag")
{
Tag? wayTag = Tag.ConvertToTag(wayReader.GetAttribute("k")!, wayReader.GetAttribute("v")!);
if(wayTag is not null)
currentTags.TryAdd(wayTag.key, wayTag.value);
HashSet<Tag> pTags = Tag.ConvertToTags(wayReader.GetAttribute("k")!, wayReader.GetAttribute("v")!);
if(pTags.Count > 0)
foreach (Tag pTag in pTags)
currentTags.TryAdd(pTag.key, pTag.value);
}
else if (wayReader.Name == "nd")
{
@ -146,31 +147,42 @@ public class RegionConverter
{
ulong node1Id = currentNodeIds[i];
ulong node2Id = currentNodeIds[i+1];
if (currentTags.ContainsKey(Tag.TagType.oneway) && (bool)currentTags[Tag.TagType.oneway] && nodeRegions.ContainsKey(node1Id) && nodeRegions.ContainsKey(node2Id))
if (nodeRegions.ContainsKey(node1Id) && nodeRegions.ContainsKey(node2Id))
{
if (currentTags.ContainsKey(Tag.TagType.forward) && !(bool)currentTags[Tag.TagType.forward])
if (currentTags.ContainsKey(Tag.TagType.oneway) && (bool)currentTags[Tag.TagType.oneway])
{
OsmEdge n21e = new OsmEdge(currentTags[Tag.TagType.id], node2Id, node1Id, nodeRegions[node2Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node2Id], n21e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node2Id], currentTags, outputPath);
if (currentTags.ContainsKey(Tag.TagType.forward) && !(bool)currentTags[Tag.TagType.forward])
{
OsmEdge n21e = new OsmEdge(currentTags[Tag.TagType.id], node2Id, node1Id,
nodeRegions[node1Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node2Id], n21e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node2Id],
currentTags, outputPath);
}
else
{
OsmEdge n12e = new OsmEdge(currentTags[Tag.TagType.id], node1Id, node2Id,
nodeRegions[node2Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node1Id], n12e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node1Id],
currentTags, outputPath);
}
}
else
{
OsmEdge n12e = new OsmEdge(currentTags[Tag.TagType.id], node1Id, node2Id, nodeRegions[node2Id]);
OsmEdge n12e = new OsmEdge(currentTags[Tag.TagType.id], node1Id, node2Id,
nodeRegions[node2Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node1Id], n12e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node1Id], currentTags, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node1Id],
currentTags, outputPath);
OsmEdge n21e = new OsmEdge(currentTags[Tag.TagType.id], node2Id, node1Id,
nodeRegions[node1Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node2Id], n21e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node2Id],
currentTags, outputPath);
}
}
else if(nodeRegions.ContainsKey(node1Id) && nodeRegions.ContainsKey(node2Id))
{
OsmEdge n12e = new OsmEdge(currentTags[Tag.TagType.id], node1Id, node2Id, nodeRegions[node2Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node1Id], n12e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node1Id], currentTags, outputPath);
OsmEdge n21e = new OsmEdge(currentTags[Tag.TagType.id], node2Id, node1Id, nodeRegions[node2Id]);
WriteWay(ref regionWaysFileStreams, nodeRegions[node2Id], n21e, outputPath);
WriteTags(ref regionTagsFileStreams, ref writtenWayTagsInRegion, nodeRegions[node2Id], currentTags, outputPath);
}
}
}
}

View File

@ -1,33 +1,183 @@
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.Json;
using OSMDatastructure;
using OSMDatastructure.Graph;
using Pathfinding;
using RenderPath;
using Region = OSMDatastructure.Region;
namespace Server;
public class Server
{
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")]
public static void Main(string[] args)
{
ConsoleWriter newConsole = new ConsoleWriter();
ConsoleWriter newConsole = new();
Console.SetOut(newConsole);
Console.SetError(newConsole);
RegionConverter.ConvertXMLToRegions("D:/stuttgart-regbez-latest.osm", "D:/stuttgart-regbez-latest");
string workingDir = "D:/stuttgart-regbez-latest";
//RegionConverter.ConvertXMLToRegions("D:/stuttgart-regbez-latest.osm", "D:/stuttgart-regbez-latest");
//RegionConverter.ConvertXMLToRegions("D:/map.osm", "D:/map");
//RegionConverter.ConvertXMLToRegions("D:/germany-latest.osm", "D:/germany-latest");
Coordinates start = new (48.7933798f, 9.8275859f);
Coordinates finish = new (48.795918f, 9.021618f);
Pathfinder result = new Pathfinder(workingDir, 2, 30).AStar(start, finish, Tag.SpeedType.car, 1);
Renderer image = Renderer.DrawPathfinder(result, Renderer.RenderType.png);
image.Save("D:/stuttgart-regbez-latest");
/*
Coordinates start = new Coordinates(48.794567f, 9.820625f);
Coordinates finish = new Coordinates(48.79593f, 9.824013f);
DateTime startTime = DateTime.Now;
OsmNode[] path = Pathfinder.CustomAStar("D:/map", start, finish, Tag.SpeedType.car).ToArray();
TimeSpan duration = DateTime.Now - startTime;
Console.WriteLine($"Took {duration.TotalMilliseconds}ms ({duration:g})");
for (int i = 0; i < path.Length - 1; i++)
if(File.Exists(@"D:\bounds"))
File.Delete(@"D:\bounds");
RegionManager rm = LoadRegions(workingDir, start, finish);
Renderer areaRender = Renderer.DrawArea(rm, Renderer.RenderType.PNG);
FileStream s = new(@"D:\bounds", FileMode.OpenOrCreate);
JsonSerializer.Serialize(s, areaRender.bounds, JsonSerializerOptions.Default);
areaRender.Save(@"D:\Base");
s.Dispose();
*/
//TestVariables(workingDir, start, finish, 12);
//GetShortestRoute("D:");
/*
string parentFolder = new DirectoryInfo(workingDir).Parent!.FullName;
Renderer.Bounds bounds = JsonSerializer.Deserialize<Renderer.Bounds>(new FileStream(@"D:\bounds", FileMode.Open));
Image baseImage = Image.FromFile(@"D:\Base.png");
Pathfinder result = new Pathfinder(workingDir, 2, 30).AStar(start,
finish, Tag.SpeedType.car, 4);
Console.WriteLine($"Calc-time {result.pathResult!.calcTime} Path-length: {result.pathResult.pathNodes.Count} Visited-nodes: {result.gScore!.Count}");
string fileName = DateTime.Now.ToFileTime().ToString();
string resultFileName = $"{new DirectoryInfo(workingDir).Name}-{fileName}.result";
result.SaveResult(Path.Join(parentFolder, resultFileName));
string renderFileName = $"{new DirectoryInfo(workingDir).Name}-{fileName}.render.png";
Image renderWeights = Renderer.DrawGScores(result.gScore, baseImage, bounds).Item1;
Image render = Renderer.DrawPath(result.pathResult, renderWeights, bounds).Item1;
render.Save(Path.Join(parentFolder, renderFileName), ImageFormat.Png);
*/
Console.Beep(400, 50);
Console.Beep(600, 50);
Console.Beep(400, 50);
Console.Beep(600, 50);
}
private static void GetShortestRoute(string directory)
{
DateTime start = DateTime.Now;
HashSet<string> allFiles = Directory.GetFiles(directory).Where(file => file.EndsWith(".result")).ToHashSet();
Dictionary<PathResult, string> results = new();
int loaded = 0;
foreach (string filePath in allFiles)
{
Console.WriteLine(path[i]);
PathResult result = PathResult.PathresultFromFile(filePath);
results.Add(result, filePath);
Console.WriteLine($"{loaded++}/{allFiles.Count()} {filePath} " +
$"Time elapsed: {DateTime.Now - start} " +
$"Remaining {((DateTime.Now - start)/loaded)*(allFiles.Count-loaded)}");
}
KeyValuePair<PathResult, string> shortest = results.MinBy(result => result.Key.distance);
KeyValuePair<PathResult, string> fastest = results.MinBy(result => result.Key.weight);
KeyValuePair<PathResult, string> calcTime = results.MinBy(result => result.Key.calcTime);
Console.WriteLine($"\nShortest:\t{shortest.Key.distance:0.0} {shortest.Key.weight:0.00} {shortest.Key.calcTime} {shortest.Value}\n" +
$"Fastest:\t{fastest.Key.distance:0.0} {fastest.Key.weight:0.00} {fastest.Key.calcTime} {fastest.Value}\n" +
$"CalcTime:\t{calcTime.Key.distance:0.0} {calcTime.Key.weight:0.00} {calcTime.Key.calcTime} {calcTime.Value}");
}
private static RegionManager LoadRegions(string workingDir, Coordinates c1, Coordinates c2)
{
float minLat = c1.latitude < c2.latitude ? c1.latitude : c2.latitude;
float minLon = c1.longitude < c2.longitude ? c1.longitude : c2.longitude;
float maxLat = c1.latitude > c2.latitude ? c1.latitude : c2.latitude;
float maxLon = c1.longitude > c2.longitude ? c1.longitude : c2.longitude;
RegionManager allRegions = new(workingDir);
for (float lat = minLat - Region.RegionSize * 3; lat < maxLat + Region.RegionSize * 3; lat += Region.RegionSize / 2)
{
for (float lon = minLon - Region.RegionSize; lon < maxLon + Region.RegionSize; lon += Region.RegionSize / 2)
{
allRegions.GetRegion(new Coordinates(lat, lon));
}
}
Console.WriteLine("Loaded needed Regions");
return allRegions;
}
[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")]
private static void TestVariables(string workingDir, Coordinates start, Coordinates finish, int threads)
{
string parentFolder = new DirectoryInfo(workingDir).Parent!.FullName;
RegionManager rm = LoadRegions(workingDir, start, finish);
Queue<Thread> calcThreads = new();
Bounds bounds = JsonSerializer.Deserialize<Bounds>(new FileStream(@"D:\bounds", FileMode.Open))!;
for (double extraTime = 1.5; extraTime >= 1; extraTime -= 0.25)
{
for (double roadFactor = 0.05; roadFactor < 5; roadFactor += 0.05)
{
double road = roadFactor;
double time = extraTime;
calcThreads.Enqueue(new Thread(() =>
{
Pathfinder testresult = new Pathfinder(workingDir, road, 30).AStar(start,
finish, Tag.SpeedType.car, time);
Image baseImage = Image.FromStream(new FileStream(@"D:\Base.png", FileMode.Open, FileAccess.Read, FileShare.Read,
(int)new FileInfo(@"D:\Base.png").Length, FileOptions.Asynchronous));
Renderer renderer = new PNGRenderer(baseImage);
renderer.bounds = bounds;
Renderer renderWeights = Renderer.DrawGScores(testresult.gScore!, Renderer.RenderType.png, renderer);
Renderer render = Renderer.DrawPath(testresult.pathResult!, Renderer.RenderType.png, renderWeights);
string fileName = $"road{road:0.00}_time{time:0.00}";
string resultFileName = Path.Combine("D:", $"{fileName}.result");
testresult.SaveResult(resultFileName);
string imageFileName = Path.Combine("D:", fileName);
render.Save(imageFileName);
Console.WriteLine($"Saved {fileName}");
}));
}
}
int totalTasks = calcThreads.Count;
int completedTasks = 0;
DateTime startTime = DateTime.Now;
HashSet<Thread> runningThreads = new();
Console.WriteLine($"Running {threads} Threads on {totalTasks} Tasks.");
while (calcThreads.Count > 0 || runningThreads.Count > 0)
{
while (runningThreads.Count < threads && calcThreads.Count > 0)
{
Thread t = calcThreads.Dequeue();
runningThreads.Add(t);
t.Start();
}
int newCompletedTasks = runningThreads.RemoveWhere(thread => !thread.IsAlive);
completedTasks += newCompletedTasks;
if (newCompletedTasks > 0)
{
TimeSpan elapsedTime = DateTime.Now - startTime;
Console.WriteLine($"To calculate: {calcThreads.Count}(+{runningThreads.Count} running)/{totalTasks} Time Average: {(elapsedTime/completedTasks)} Elapsed: {elapsedTime} Remaining: {(elapsedTime/completedTasks*calcThreads.Count)}");
}
}
Console.WriteLine();*/
}
}

View File

@ -9,9 +9,11 @@
<ItemGroup>
<ProjectReference Include="..\Pathfinding\Pathfinding.csproj" />
<ProjectReference Include="..\RenderPath\RenderPath.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="7.0.0" />
<PackageReference Include="System.Runtime.Serialization.Json" Version="4.3.0" />
</ItemGroup>