A* Algorithm System.StackOverflowException - c#

public List<Location2D> Path(Location2D start, Location2D goal)
{
openset = new List<NodeInfo>(); // The set of tentative nodes to be evaluated, initially containing the start node.
closedset = new List<NodeInfo>(); // The set of nodes already evaluated.
path = new List<Location2D>(); // The path result.
came_from = new Dictionary<Location2D, Location2D>();
NodeInfo Start = new NodeInfo();
Start.SetLoction(start.X, start.Y);
Start.H = GetHValue(start, goal);
openset.Add(Start);
while (openset.Count > 0) { // while openset is not empty
NodeInfo current = CheckBestNode(); //the node in openset having the lowest f_score[] value
if (current.Location.Equals(goal)) {
ReconstructPathRecursive(current.Location);
return path;
}
for (int i = 0; i < 8; i++) { // neighbor nodes.
NodeInfo neighbor = new NodeInfo();
neighbor.SetLoction((ushort)(current.Location.X + ArrayX[i]), (ushort)(current.Location.Y + ArrayY[i]));
bool tentative_is_better = false;
if (closedset.Contains(neighbor))
continue;
if (!map.Cells[neighbor.Location.X, neighbor.Location.Y].Walkable) { closedset.Add(neighbor); continue; }
Double tentative_g_score = current.G + DistanceBetween(current.Location, neighbor.Location);
if (!openset.Contains(neighbor)) {
openset.Add(neighbor);
neighbor.H = GetHValue(neighbor.Location, goal);
tentative_is_better = true;
} else if (tentative_g_score < neighbor.G) {
tentative_is_better = true;
} else {
tentative_is_better = false;
}
if (tentative_is_better) {
came_from[neighbor.Location] = current.Location;
neighbor.G = tentative_g_score;
}
}
}
return null;
}
private void ReconstructPathRecursive(Location2D current_node)
{
Location2D temp;
if (came_from.TryGetValue(current_node, out temp)) {
path.Add(temp);
ReconstructPathRecursive(temp);
} else {
path.Add(current_node);
}
}
so am Implementing A* Algorithm and when it find the Goal it goes to the ReconstructPathRecursive
and then the app crash and throw this exception An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
and This thread is stopped with only external code frames on the call stack. External code frames are typically from framework code but can also include other optimized modules which are loaded in the target process.
idk what's wrong!

It doesn't really have to be recursive, because it's tail recursive. So you can rewrite it like this:
private void ReconstructPathIterative(Location2D current_node)
{
Location2D temp;
while (came_from.TryGetValue(current_node, out temp))
{
path.Add(temp);
current_node = temp;
}
path.Add(current_node);
}
That only helps if the path was simply too long to fit on the stack, not if it was infinite.

I fixed it by adding NodeInfo Parent {get; set; } as a filed inside the NodeInfo class, and I add new List<NodeInfo> called Nodes when tentative is better :-
if (tentative_is_better) {
neighbor.Parent = current;
nodes.Add(neighbor);
neighbor.G = tentative_g_score;
}
then when it finds the goal :-
if (current.Location.Equals(goal)){
ReconstructPath(current);
path.Reverse();
return path;
}
where ReconstructPath :-
private void ReconstructPath(NodeInfo current) {
if (current.Parent == null) return;
path.Add(current.Parent.Location);
ReconstructPath(current.Parent);
}
and it works fine now.

Related

C# loop edit (I can't code, just trying to make a simple edit)

I need this pre-existing script to loop every forever, I do not know much code and am unable to edit this myself, I'm hoping one of you smart boys can assist in the editing of this script.
This script is C# built for a game called Space Engineers where it takes information from a solar panel to determine time of day/light level and respond by turning on the lights or turning off the lights.
//How to use:
//Setup a timer that triggers it self and this programmable block every 5-10 minutes. Then set the light strength(
//when the solar panel gets less kW's than that, the lights are turned on). Then set measureSolarPanelName to
//the customname of the solar panel that you want to use to measure the light. If you want to use a prefix, set
//usePrefix to true und set a prefix. When you set overwrite to true, this script will stop
//working until you deactivate overwrite(= false), for eg. battles.
//Thank you for using my script :)
//Settings:
int lightStrength = 10;
string measureSolarPanelName = "Solar Panel";
bool overwrite = false;
bool usePrefix = false;
string prefix = "[NL]";
//Code
public void Main(string argument) {
if (getSolarPower() < lightStrength) {
triggerLights(1);
} else {
triggerLights(0);
}
}
int getSolarPower () {
bool watts;
string info = GridTerminalSystem.GetBlockWithName(measureSolarPanelName).DetailedInfo;
var lines = info.Split('\n');
var output = lines[1].Split(':')[1].Trim();
var final = output.Replace(" kW", "");
if (final.Contains("W")) { final = final.Replace(" W", ""); watts = true; } else watts = false;
var finalb = final.Split ('.')[0];
if (watts) { finalb = "1"; }
return Int32.Parse(finalb);
}
void triggerLights(int status) {
if (status == 1 && !overwrite) {
List<IMyInteriorLight> lights = new List<IMyInteriorLight> ();
GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(lights);
List<IMyReflectorLight> spotlights = new List<IMyReflectorLight> ();
GridTerminalSystem.GetBlocksOfType<IMyReflectorLight>(spotlights);
for (int i = 0; i < lights.Count; i++) {
if (getPrefixBool(lights[i].CustomName)) {
lights[i].GetActionWithName ("OnOff_On").Apply(lights[i]);
}
}
for (int i = 0; i < spotlights.Count; i++) {
if (getPrefixBool(spotlights[i].CustomName)) {
spotlights[i].GetActionWithName("OnOff_On").Apply(spotlights[i]);
}
}
}
else
if (status == 0 && !overwrite) {
List<IMyInteriorLight> lights = new List<IMyInteriorLight> ();
GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(lights);
List<IMyReflectorLight> spotlights = new List<IMyReflectorLight> ();
GridTerminalSystem.GetBlocksOfType<IMyReflectorLight>(spotlights);
for (int i = 0; i < lights.Count; i++) {
if (getPrefixBool(lights[i].CustomName)) {
lights[i].GetActionWithName("OnOff_Off").Apply(lights[i]);
}
}
for (int i = 0; i < spotlights.Count; i++) {
if (getPrefixBool(spotlights[i].CustomName)) {
spotlights[i].GetActionWithName("OnOff_Off").Apply(spotlights[i]);
}
}
}
}
bool getPrefixBool (string name) {
if (usePrefix) {
if (name.StartsWith(prefix)) {
return true;
} else return false;
} else return true;
}
I haven't tried much at this point as I can't exactly code... I have found a couple lines but they don't seem to work.

SortedSet inserting element out of sort

I’ve written an implementation of A* that relies on sorting nodes by their F score in a sortedSet.
The sorting, in some cases, seems to insert a Node object at the 'Min' value when its compared 'F' value is actually the second lowest rather than the Min, as described. I'm completely baffled as to why this is happening. I believe it's causing the knock-on effect of causing nodeTree.Remove and nodeTree.RemoveWhere to fail, but that might be the actual cause of the issue, I'm honestly not sure - though I wouldn't know how to fix it if it is.
This is the comparer used. I assume it's relatively obvious that I'm not exactly sure how to implement these, but I think this should work as I intend.
public class FValueFirst : Comparer<PathfindingAgent.Node>
{
public override int Compare(PathfindingAgent.Node x, PathfindingAgent.Node y)
{
int result = x.F.CompareTo(y.F);
if (result == 0)
{
result = y.G.CompareTo(x.G);
}
if(x == y)
{
result = 0;
}
return result;
}
}
This is the Node object, for reference.
public class Node
{
public Cell cell;
public float G;
public float H;
public bool Opened;
public bool Closed;
public Node Previous;
public float F { get => G + H; }
}
This is the function it all occurs in. The result is deterministic, thankfully. Depending on the current destID and the particular layout of the grid's obstacles it will always get out of sort on the same iteration.
public void PathTo(Vector3Int destID)
{
SortedSet<Node> nodeTree = new SortedSet<Node>(new FValueFirst());
Vector3Int radius = PathfindingGrid.Instance.GridRadius;
NodeGrid = new Node[radius.x * 2 + 1, radius.y * 2 + 1, radius.z * 2 + 1];
Node startNode = new Node()
{
cell = PathfindingGrid.Cells[CurrentID.x, CurrentID.y, CurrentID.z],
G = 0,
H = 0
};
Node endNode = new Node()
{
cell = PathfindingGrid.Cells[destID.x, destID.y, destID.z],
G = 0,
H = 0
};
Vector3Int sID = startNode.cell.ID;
Vector3Int eID = endNode.cell.ID;
NodeGrid[sID.x, sID.y, sID.z] = startNode;
NodeGrid[eID.x, eID.y, eID.z] = endNode;
if (endNode.cell.IsOccupied) return;
nodeTree.Add(startNode);
int iterations = 0;
while(true)
{
Node node;
node = nodeTree.Min;
node.Closed = true;
nodeTree.RemoveWhere(n => n == node);
if(node == nodeTree.Min)
{
throw new Exception($"Incorrect node was removed from the tree");
}
if (node == endNode)
{
List<Node> chain = BacktraceChain(node);
Debug.Log($"Path found from {CurrentID} to {destID} with score {endNode.G} traversing {chain.Count} cells in {iterations} iterations");
DrawLine(chain, Color.white);
break;
}
List<Node> neighbours = GetNeighbours(node);
foreach(Node neighbour in neighbours)
{
if (neighbour == startNode || neighbour.Closed) continue;
float newg = Vector3Int.Distance(node.cell.ID, neighbour.cell.ID) + node.G;
if (!neighbour.Opened || newg < neighbour.G)
{
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
if(!neighbour.Opened)
{
nodeTree.Add(neighbour);
neighbour.Opened = true;
}
else
{
nodeTree.RemoveWhere(n => n == neighbour);
nodeTree.Add(neighbour);
}
}
}
iterations++;
}
}
For posterity, I solved the issue - it was due to my inexperience with the SortedList type.
This code, found near the end of the function was to blame
if (!neighbour.Opened || newg < neighbour.G)
{
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
if(!neighbour.Opened)
{
nodeTree.Add(neighbour);
neighbour.Opened = true;
}
else
{
nodeTree.RemoveWhere(n => n == neighbour);
nodeTree.Add(neighbour);
}
Specifically, an item in a tree cannot have its compared values modified to the point where it no longer compares correctly in that index. The item must first be removed from the list, modified, and readded.
My guess in hindsight is that, though removed immediately after modification, the tree is unable to be sufficiently traversed to access the target item due to the modification.
Thus my solution was to simply re-arrange the block so that the removal and addition occured on either side of the modification respectively, like so:
if (!neighbour.Opened || newg < neighbour.G)
{
if (neighbour.Opened)
{
if (!nodeTree.Remove(neighbour)) throw new Exception($"{neighbour} was not removed from tree");
}
else
{
neighbour.Opened = true;
}
neighbour.G = newg;
neighbour.H = ManhattanHeuristic(neighbour, endNode);
neighbour.Previous = node;
nodeTree.Add(neighbour);
}

Adding nodes by value

I am trying to add nodes in a sorted manner to my linked list. My code just keeps adding to the end if the value is less than the end of the linked list. I am not sure how to fix this or if I am not fully checking for the right scenario.
I have tried to increment current until it is greater than the nodeToAdd to place the node between, but it always just places it at the end.
public void AddOrdered(int value)
{
LinkedListNode nodeToAdd = new LinkedListNode(value);
LinkedListNode cur = m_first;
if (m_first == null)
m_first = nodeToAdd;//new LinkedListNode(value);
else if (nodeToAdd.m_data < m_first.m_data)
{
AddAtFront(value);
}
else if (nodeToAdd.m_data < cur.m_next.m_data)
{
LinkedListNode temp = new LinkedListNode(value);
temp = m_first.m_next;
m_first.m_next = nodeToAdd;
nodeToAdd.m_next = temp;
}
else
{
AddAtEnd(value);
}
}
supplement add at end/front methods--which are working fine
public void AddAtEnd(int value)
{
LinkedListNode cur = m_first;
if (m_first == null)
{
LinkedListNode lnl = new LinkedListNode(value);
m_first = lnl;
}
while (cur.m_next != null)
{
cur = cur.m_next;
}
cur.m_next = new LinkedListNode(value);
}
public void AddAtFront(int value)
{
if (m_first == null)
{
LinkedListNode ln = new LinkedListNode(value);
m_first = ln;
}
else
{
LinkedListNode lnl = new LinkedListNode(value);
lnl.m_next = m_first;
m_first = lnl;
}
}
The values should get added in order but the output is placing them at the very end of the linked list unless new min/maxs are entered as values.
First I am assuming that m_first is your first node. With this as an assumption the code would be as follows:
public void AddOrdered(int value)
{
LinkedListNode nodeToAdd = new LinkedListNode(value);
LinkedListNode cur;
if (m_first == null || m_first.data >= nodeToAdd.data)
{
nodeToAdd.next = m_first;
m_first = nodeToAdd;
}
else
{
cur = m_first;
while (cur.next != null &&
cur.next.data < nodeToAdd.data)
cur = cur.next;
nodeToAdd.next = cur.next;
cur.next = nodeToAdd;
}
}

Loop not finding elements after going to new page.StaleElementReferenceException

List<IWebElement> shittyBiz = new List<IWebElement>();
var myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
for (int i = 0;i<=1000;i++){
myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
foreach (IWebElement business in myEles)
{
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var starRating = " ";
try
{
starRating = business.FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title");
}
catch (OpenQA.Selenium.NoSuchElementException)
{
MessageBox.Show("No stars");
continue;
}
starRating = Regex.Replace(starRating, #"[A-Za-z\s]", string.Empty);
float stars = float.Parse(starRating);
MessageBox.Show(stars.ToString());
if (stars <= 3)
{
//shittyBiz.Add(starRating);
MessageBox.Show("Shitty");
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
var bizName = business.FindElement(By.CssSelector(".biz-name"));
MessageBox.Show(bizName.Text);
shittyBiz.Add(bizName);
var bizLocation = business.FindElement(By.CssSelector(".secondary-attributes"));
MessageBox.Show(bizLocation.Text);
shittyBiz.Add(bizLocation);
}
else
{
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
MessageBox.Show("Too good");
}
}
try
{
driverGC.FindElement(By.CssSelector("div.arrange_unit > a.u-decoration-none")).Click();
continue;
}
catch (OpenQA.Selenium.NoSuchElementException)
{
MessageBox.Show("No more pages");
return;
//driverGC.Quit();
}
}
I can get the program to run fine the first time, but after it uses the try at the end, to go to the next page, i get the StaleElementReferenceException error almost immediately on the starRating in the first try. I have tried everything that I can think of, but not sure why it is throwing me that error.
When the DOM is refreshed or changed the driver loses all the elements it previously located. After moving to the new page myEles is not valid any more and that's why you get StaleElementReferenceException on business when you trying to use it to locate another element. The solution is to locate myEles each iteration and keep the location using indexes with for loop
int size = 1;
for (int i = 0; i < size; ++i)
{
var myEles = driverGC.FindElements(By.CssSelector("div.search-result"));
size = myEles.Count();
driverGC.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
var starRating = " ";
try
{
starRating = myEles[i].FindElement(By.CssSelector("div.biz-rating > div.i-stars")).GetAttribute("title");
}
//...
// and don't forget to go back
driver.Navigate().Back();
}

How to avoid this stackoverflow exception?

Here is the situation, I am developing a binary search tree and in each node of the tree I intend to store the height of its own for further balancing the tree during avl tree formation. Previously I had an iterative approach to calculate the height of a node during balancing the tree like the following.
(The following code belongs to a class called AVLTree<T> which is a child class of BinarySearchTree<T>)
protected virtual int GetBalance(BinaryTreeNode<T> node)
{
if(node != null)
{
IEnumerable<BinaryTreeNode<T>> leftSubtree = null, righSubtree = null;
if (node.Left != null)
leftSubtree = node.Left.ToEnumerable(BinaryTreeTraversalType.InOrder);
if (node.Right != null)
righSubtree = node.Right.ToEnumerable(BinaryTreeTraversalType.InOrder);
var leftHeight = leftSubtree.IsNullOrEmpty() ? 0 : leftSubtree.Max(x => x.Depth) - node.Depth;
var righHeight = righSubtree.IsNullOrEmpty() ? 0 : righSubtree.Max(x => x.Depth) - node.Depth;
return righHeight - leftHeight;
}
return 0;
}
But it was incurring a lot of performance overhead.
Performance of an AVL Tree in C#
So I went for storing the height value in each node at the time of insertion in the BinarySearchTree<T>. Now during balancing I am able to avoid this iteration and I am gaining the desired performance in AVLTree<T>.
But now the problem is if I try to insert a large number of data say 1-50000 sequentially in BinarySearchTree<T> (without balancing it), I am getting StackoverflowException. I am providing the code which is causing it. Can you please help me to find a solution which will avoid this exception and also not compromise with the performance in its child class AVLTree<T>?
public class BinaryTreeNode<T>
{
private BinaryTreeNode<T> _left, _right;
private int _height;
public T Value {get; set; }
public BinaryTreeNode<T> Parent;
public int Depth {get; set; }
public BinaryTreeNode()
{}
public BinaryTreeNode(T data)
{
Value = data;
}
public BinaryTreeNode<T> Left
{
get { return _left; }
set
{
_left = value;
if (_left != null)
{
_left.Depth = Depth + 1;
_left.Parent = this;
}
UpdateHeight();
}
}
public BinaryTreeNode<T> Right
{
get { return _right; }
set
{
_right = value;
if (_right != null)
{
_right.Depth = Depth + 1;
_right.Parent = this;
}
UpdateHeight();
}
}
public int Height
{
get { return _height; }
protected internal set
{
_height = value;
if (Parent != null) {
Parent.UpdateHeight();
}
}
}
private void UpdateHeight()
{
if (Left == null && Right == null) {
return;
}
if(Left != null && Right != null)
{
if (Left.Height > Right.Height)
Height = Left.Height + 1;
else
Height = Right.Height + 1;
}
else if(Left == null)
Height = Right.Height + 1;
else
Height = Left.Height + 1;
}
}
public class BinarySearchTree<T>
{
private readonly Comparer<T> _comparer = Comparer<T>.Default;
public BinarySearchTree()
{
}
public BinaryTreeNode<T> Root {get; set;}
public virtual void Add(T value)
{
var n = new BinaryTreeNode<T>(value);
int result;
BinaryTreeNode<T> current = Root, parent = null;
while (current != null)
{
result = _comparer.Compare(current.Value, value);
if (result == 0)
{
parent = current;
current = current.Left;
}
if (result > 0)
{
parent = current;
current = current.Left;
}
else if (result < 0)
{
parent = current;
current = current.Right;
}
}
if (parent == null)
Root = n;
else
{
result = _comparer.Compare(parent.Value, value);
if (result > 0)
parent.Left = n;
else
parent.Right = n;
}
}
}
I am getting the StackoverflowException in calculating the height at the following line
if (Parent != null) {
Parent.UpdateHeight();
}
in the Height property of BinaryTreeNode<T> class. If possible please suggest me some work around.
BTW, thanks a lot for your attention to read such a long question :)
When you add a node you compute the height by iterating over all the parent nodes recursively. A .NET process has limited stack space and given a big tree you will consume all stack space and get a StackOverflowException. You can change the recursion into an iteration to avoid consuming stack space. Other languages like functional languages are able to recurse without consuming stack space by using a technique called tail recursion. However, in C# you will have to manually modify your code.
Here are modified versions of Height and UpdateHeight in BinaryTreeNode<T> that doesn't use recursion:
public int Height {
get { return _height; }
private set { _height = value; }
}
void UpdateHeight() {
var leftHeight = Left != null ? Left.Height + 1 : 0;
var rightHeight = Right != null ? Right.Height + 1 : 0;
var height = Math.Max(leftHeight, rightHeight);
var node = this;
while (node != null) {
node.Height = height;
height += 1;
node = node.Parent;
}
}
You can add a tail. call in il, decompile the file and then compile it again.
Example:
.... IL_0002: add
tail.
IL_0003: call ...
IL_0008: ret
Example on compiling it again:
ilasm C:\test.il /out=C:\TestTail.exe
(this is probably not what you want, but again it's just an example)
I'm sure you can figure it out and make it work, it's not to hard.
The big downside is that recompilation will get rid of your tail call so I recommend to set up a build task in msbuild to do it automatically for you.
I think I found the solution, I modified the code as follows and it worked like a charm
public int Height
{
get { return _height; }
protected internal set
{
_height = value;
}
}
private void UpdateHeight()
{
if (Left == null && Right == null) {
return;
}
if(Left != null && Right != null)
{
if (Left.Height > Right.Height)
Height = Left.Height + 1;
else
Height = Right.Height + 1;
}
else if(Left == null)
Height = Right.Height + 1;
else
Height = Left.Height + 1;
var parent = Parent;
while (parent != null) {
parent.Height++;
parent = parent.Parent;
}
}
Thanks a lot guys who spend some time for me to tried to find out the solution.
If you are inserting large amounts of data in one go I would think you'd be better of batch inserting the data without the call to Parent.UpdateHeight then walk the tree setting the height as you go.
Adding future nodes I would walk the tree, starting at the root, incrementing the height as you go.

Categories

Resources