The evaluation function of A* Search is, according to AI: A Modern Approach, f(x) = h(x) + g(x), where f(x) is the evaluation function, h(x) the heuristic function (Euclidian straight line in my case), and g(x) the path-cost. f(x) for greedy search is simply f(x) = h(x).
To test these I made a visualization program.
With obstacle:
As you can see, the greedy search was far more effective than A*. This surprised me, so I wonder if this is expected and whether there is something wrong with my A*-code; either the heuristic or the priority queue.
int heuristic(Node n) {
int i=distanceFrom(n.state, grid.goalState) + n.state.pCost;
return i;
}
PriorityQueue<Node> front = new PriorityQueue<Node>(30, new Comparator<Node>() {
// override compare method
public int compare(Node i, Node j) {
if (heuristic(i) > heuristic(j)) {
return 1;
}
else if (heuristic(i) < heuristic(j)) {
return -1;
}
else {
return 0;
}
}
});
If I try making pCost less significant and more similar to Greedy by dividing it by an integer, it will perform better. Is A* supposed to perform like this?
The entire A* execute-function looks like this:
public void execute() {
SwingWorker worker = new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
boolean retGoal = false;
PriorityQueue<Node> front = new PriorityQueue<Node>(30, new Comparator<Node>() {
// override compare method
public int compare(Node i, Node j) {
if (heuristic(i) > heuristic(j)) {
return 1;
}
else if (heuristic(i) < heuristic(j)) {
return -1;
}
else {
return 0;
}
}
});
Hashtable<State,Node> reached = new Hashtable<State,Node>();
State s;
Node goal = null;
n = new Node(grid.startState, null);
int pCost = 0;
n.pathCost = pCost;
n.state.pCost = pCost;
front.add(n);
reached.put(n.state, n);
n.state.front=true;
panel.repaint();
while(!front.isEmpty()) {
Thread.sleep(Main.delay);
n.state.front=false;
n=front.poll();
if(grid.isGoal(n.state)) {
goal = n;
break;
}
pCost=n.state.pCost+1;
panel.repaint();
for (Node child : expand(n, grid)) {
s = child.state;
if(!reached.containsKey(s) && !s.isObstacle) {
s.pCost = pCost; //steps from goal
}
if((!reached.containsKey(s) || heuristic(child) < heuristic(reached.get(s))) && !s.isObstacle) {
s.reached = true;
s.front = true;
reached.put(s, child);
front.add(child);
}
panel.repaint();
}
}
if(goal != null) {
Node n = goal.parent;
while(n.parent != null) {
n.state.isPath=true;
n = n.parent;
}
}
panel.repaint();
return null;
}
};
worker.execute();
}
Related
I have an A* pathfinding algorithm that I've used for a Spigot plugin which worked fine. I then added a requirements system so it won't try and pathfind through places it shouldn't. Now it seems REALLY slow, and it looks like it has nothing to do with the requirements code itself, and more to do with the algorithm having many more incorrect paths when calculating. I seem to be getting 1500ms+ on this, which is definitely not good xD
Here is the pathfinder code:
public Path calculate(PathfinderGoal goal, PathScorer scorer, List<PathRequirement> requirements, int maxNodes) {
PathNode start = toNode(npc.getLocation());
PathNode end = toNode(goal.getLocation());
List<PathNode> open = new ArrayList<>() {{ add(start); }};
List<PathNode> navigated = new ArrayList<>();
start.setF(scorer.computeCost(start, end));
Timer timer = new Timer().start();
while (!open.isEmpty()) {
PathNode current = null;
for (PathNode node : open) {
if (current == null || node.getH() < current.getH()) {
current = node;
}
}
if (scorer.computeCost(current, end) < 1 || (navigated.size() >= maxNodes && maxNodes != -1)) {
navigated.add(navigated.size() < maxNodes ? end : current);
return reconstruct(navigated, navigated.size() - 1);
}
open.remove(current);
current.close();
for (PathNode node : current.getNeighbors()) {
if (node.isClosed()) {
continue;
}
double tentG = current.getG() + scorer.computeCost(current, node);
if (!open.contains(node) || tentG < node.getG()) {
boolean requirementsMet = true;
for (PathRequirement requirement : requirements) {
requirement.setNavigated(navigated);
if (!navigated.isEmpty() && !requirement.canMoveToNewNode(navigated.get(navigated.size() - 1), node)) {
requirementsMet = false;
break;
}
}
if (!navigated.contains(current)) {
navigated.add(current);
}
node.setG(tentG);
node.setH(scorer.computeCost(node, end));
node.setF(tentG + node.getH());
if (!open.contains(node) && requirementsMet) {
open.add(node);
}
}
}
Bukkit.broadcastMessage("Open Set Size: " + open.size());
Bukkit.broadcastMessage(timer.stop() + "ms");
}
return null;
}
private Path reconstruct(List<PathNode> navigated, int index) {
final PathNode current = navigated.get(index);
Path withCurrent = new Path(new ArrayList<>() {{ add(current); }});
if (index > 0 && navigated.contains(current)) {
return reconstruct(navigated, index - 1).append(withCurrent);
}
return withCurrent;
}
And here is the PathNode class:
public PathNode(Pathfinder pathfinder, int x, int y, int z) {
this.pathfinder = pathfinder;
this.x = x;
this.y = y;
this.z = z;
}
#Override
public boolean equals(Object other) {
if (!(other instanceof PathNode otherNode)) {
return false;
}
return otherNode.x == x && otherNode.y == y && otherNode.z == z;
}
public List<PathNode> getNeighbors() {
return new ArrayList<>() {
{
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
for (int z = -1; z <= 1; z++) {
add(new PathNode(pathfinder, PathNode.this.x + x, PathNode.this.y + y, PathNode.this.z + z));
}
}
}
}
};
}
public Location getLocation() {
return new Location(pathfinder.getNPC().getLocation().getWorld(), x, y, z);
}
public double getF() {
return F;
}
public void setF(double f) {
this.F = f;
}
public double getG() {
return G;
}
public void setG(double g) {
this.G = g;
}
public double getH() {
return H;
}
public void setH(double h) {
this.H = h;
}
public boolean isClosed() {
return closed;
}
public void close() {
this.closed = true;
}
Valid Requirements Class:
public class ValidPathRequirement extends PathRequirement {
#Override
public boolean canMoveToNewNode(PathNode from, PathNode to) {
Block fromBlock = from.getLocation().getBlock();
Block toBlock = to.getLocation().getBlock();
boolean validHeight = toBlock.getType().isAir() && toBlock.getRelative(BlockFace.UP).getType().isAir(); // checks if is player height
boolean validGround = toBlock.getRelative(BlockFace.DOWN).getType().isSolid(); // is there a block underneath that they can stand on?
boolean validFromPrev = toBlock.getLocation().subtract(fromBlock.getLocation()).getY() <= 1; // is it max one block higher than the last one?
// is this one causing issues?
Location fromLocDist = from.getLocation().clone();
Location toLocDist = to.getLocation().clone();
toLocDist.setY(fromLocDist.getY());
boolean validDistance = fromLocDist.distance(toLocDist) <= 1;
return validHeight && validGround && validFromPrev;
}
}
Without looking at the rest of the algorithm, the first thing that stands out is that your data structures are incorrect. The "open" list needs to be a Priority Queue, and "closed" (or "navigated") should be a set.
Hello to all once again,
I've been assigned to print my binary tree in a way where we're supposed to turn our head to the left and look at it sideways - It will make sense when I provide an image.
I don't know if my Insert Method or if my showTree Method is wrong.
Here is my InsertMethod:
public void insert(Keyed item)
{
_root = insert(_root, item);
}
private TNode insert (TNode myRoot,Keyed item)
{
if(myRoot == null)
{
TNode newNode = new TNode();
newNode.data = item;
newNode.left = null;
newNode.right = null;
return newNode;
}
int comp = item.KeyComp(myRoot.data);
if(comp < 0)
{
myRoot.left = insert(myRoot.left, item);
}
else if (comp > 0)
{
myRoot.right = insert(myRoot.right, item);
}
return myRoot;
}
Here is my showTree Method:
public void showTree()
{
showTree(_root,1);
}
private void showTree(TNode myRoot,int myLevel)
{
if(myRoot == null)
{
return;
}
for(int i = 0; i < myLevel; i++)
{
System.out.print("\t");
}
showTree(myRoot.right, myLevel + 1);
System.out.println(myRoot.data.toStr());
showTree(myRoot.left, myLevel + 1);
}
If there are any additional methods needed in order to help - I can submit it, but I honestly don't know if my insert method is not doing something correctly, or if my ShowTree Method is not spacing out my Binary Tree correctly.
I would deeply appreciate some help!
Thanks!
Try printing the right node before you print the indentations for the current node. Something like this:
private void showTree(TNode myRoot,int myLevel)
{
if(myRoot == null)
{
return;
}
showTree(myRoot.right, myLevel + 1);
for(int i = 0; i < myLevel; i++)
{
System.out.print("\t");
}
System.out.println(myRoot.data.toStr());
showTree(myRoot.left, myLevel + 1);
}
Also I think you should start at level 0, call showTree(_root,0);
I personally think it would be more readable if you would combine the indentation to one string and then print it. something like this:
private void showTree(TNode myRoot,int myLevel)
{
if(myRoot == null)
{
return;
}
String currentNodeIdentation = "";
for(int i = 0; i < myLevel; i++)
{
currentNodeIdentation += "\t";
}
showTree(myRoot.right, myLevel + 1);
System.out.println(currentNodeIdentation + myRoot.data.toStr());
showTree(myRoot.left, myLevel + 1);
}
Or if you have java 11 you can even use currentNodeIdentation = "\t".repeat(myLevel).
I have implemented a depth first search (recursive) for the 8 puzzle problem in Java:
protected PuzzleState depthFirstSearch(PuzzleState state) {
PuzzleState start = this.getStartState();
PuzzleState goal = this.getGoalState();
PuzzleState stop = null;
int limit = 35;
int depth = state.getDepth();
boolean tooDeep = false;
if (state.equals(goal)) {
return state;
} else {
if (depth == limit) {
return stop;
} else {
Collection<Integer> actions = PuzzleAction.getPuzzleActions();
for (Integer action : actions) {
PuzzleState starter = start;
PuzzleState next = state.succ(action);
if (next != null) {
starter = depthFirstSearch(next);
}
if (starter == stop) {
tooDeep = true;
} else {
if (!starter.equals(start)) {
return starter;
}
}
}
}
}
if (tooDeep)
return stop;
else
return start;
}
I don't know what I have to change to transform it to a iterative deepening depth search. I know that there is no limit for the depth, because it increases in every round.
Tried this:
protected PuzzleState iterativeDeepSearch(PuzzleState state) {
int depth = state.getDepth();
for(int limit = 1; limit < depth; limit ++){
depthFirstSearch(state, limit);
}
}
Does anyone know how to change it to the needed IDS?
Thank you in advance!
I'm quite new to pathfinding and recently got A-Star working for the first time in Java with Libgdx, but it has some flaws, it doesnt always find the fastest path , or the program simply kills itself(because it's too slow?) :/
(Input/Output here: Imgur album: White = untouched Node, green = start, red = target, blue = path, yellow = node is on closed list but unrelevant)
The rest of the code can be found on Github.
This is the code for the Algorithm itself:
Node lastNode;
Node[] neighborNodes;
int lowestF = 2000;
Node bestNode;
public void findPath() {
for(int x = 0; x < map.worldWidth; x++) {
for(int y = 0; y < map.worldHeight; y++) {
nodes[x][y].calculateHeuristic(targetNode);
}
}
lastNode = startNode;
while(lastNode != targetNode || !openList.isEmpty()) {
neighborNodes = map.getNeighbors(lastNode);
for(Node node:neighborNodes) {
if(node != null)
if(node.state != State.BLOCKED && !closedList.contains(node)) {
openList.add(node);
node.parentNode = lastNode;
}
}
lowestF = 1000;
for(Node node:openList) {
if(node.f <= lowestF) {
lowestF = node.f;
bestNode = node;
}
}
if(openList.isEmpty() && bestNode != targetNode) {
System.out.println("No Path possible");
return;
}
openList.remove(bestNode);
closedList.add(bestNode);
lastNode = bestNode;
lastNode.setState(State.SEARCHED);
}
reconstructPath();
}
public void reconstructPath() {
Node lastNode = targetNode;
while(lastNode != startNode) {
lastNode = lastNode.parentNode;
lastNode.setState(State.PATH);
}
setStartAndEnd();
}
And the Node Class:
public class Node {
public enum State {
NORMAL, BLOCKED, START, END, SEARCHED, PATH
}
public State state;
int xPos, yPos;
Color color;
Node parentNode;
int f;
int movementCost = 10;
int heuristic;
public Node(int x, int y) {
xPos = x;
yPos = y;
setState(State.NORMAL);
}
public void setState(State newState) {
state = newState;
}
public boolean isNodeClicked() {
int inputX = Gdx.input.getX();
int inputY = Gdx.graphics.getHeight() - Gdx.input.getY();
if(inputX > xPos*32 && inputX < xPos*32+32 &&
inputY > yPos*32 && inputY < yPos*32+32) {
return true;
}
return false;
}
public void calculateHeuristic(Node targetNode) {
heuristic = (Math.abs((xPos-targetNode.xPos)) + Math.abs((yPos-targetNode.yPos))) * movementCost;
f = movementCost+heuristic;
}
public int calculateHeuristic(Node finishNode, int useless) {
return (Math.abs((xPos-finishNode.xPos)) + Math.abs((yPos-finishNode.yPos))) * movementCost;
}
}
At the moment I'm using a 2-dimensional array for the map or nodes and Arraylist for open and closed list.
It'd be much appreciated if somebody could help me get my A-star to behave and explain to me what I did wrong, I would also be very grateful for any other criticism, since I want to improve my programming :)
Thanks for your help in Advance :)
Your problem is here:
public void calculateHeuristic(Node targetNode) {
heuristic = (Math.abs((xPos-targetNode.xPos)) + Math.abs((yPos- targetNode.yPos))) * movementCost;
f = movementCost+heuristic;
}
Your calculation of your heuristic is wrong, because your calculation of your movementCost is wrong. The cost of a node is not a fixed value. It's the summation of all of the costs to move between nodes along the path to that node so far. So your node should actually have a function,
public int calculateCost(){
if(parentNode != null){
return movementCost + parentNode.calculateCost();
} else{
return movementCost;
}
}
And your heuristic thus becomes:
public void calculateHeuristic(Node targetNode) {
heuristic = (Math.abs((xPos-targetNode.xPos)) + Math.abs((yPos- targetNode.yPos))) * movementCost;
f = calculateCost()+heuristic;
}
Your other problems look like they probably all come from the various typos/logical errors I mentioned in the comments (while(...||openSet.isEmpty()) instead of while(...|| !openSet.isEmpty()), etc)
My issue is more semantic than functional, As the code does seem to implement the deQueue and enQueue functions correctly.
The reheapDown and reheapUp functions are being used incorrectly, And i believe the issue lies in my heap function
package priqueue;
public class Hosheap{
private Patient[] elements;
private int numElements;
public Hosheap(int maxSize)
{
elements= new Patient[maxSize];
numElements=maxSize;
}
public void ReheapDown(int root,int bottom)
{
int maxChild;
int rightChild;
int leftChild;
leftChild=root*2+1;
rightChild=root*2+2;
if (leftChild<=bottom)
{
if(leftChild==bottom)
maxChild=leftChild;
else
{
if(elements[leftChild].getPriority() <= elements[rightChild].getPriority())
maxChild=rightChild;
else
maxChild=leftChild;
}
if(elements[root].getPriority()<elements[maxChild].getPriority())
{
Swap(root,maxChild);
ReheapDown(maxChild,bottom);
}
}
}
public void ReheapUp(int root,int bottom)
{
int parent;
if(bottom>root)
{
parent=(bottom-1)/2;
if(elements[parent].getPriority()<elements[bottom].getPriority())
{
Swap(parent,bottom);
ReheapUp(root,parent);
}
}
}
public void Swap(int Pos1, int Pos2)
{
Patient temp;
temp = elements[Pos1];
elements[Pos1]=elements[Pos2];
elements[Pos2]=temp;
}
public Patient getElement(int e)
{
return elements[e];
}
public void setElement(Patient p, int n)
{
elements[n]=p;
}
}
The idea is to rearrange a simple priority queue system so when a patient object is removed, ReheapUp or down correctly rearranges the queue, Which the code does not accomplish. Should i also include the priority queue code, Or is this already too lengthy?
I am using NetBeans IDE 6.0.1, If that helps.
Depending on your usage requirements, the answer relating to TreeSets will most probably do what you want.
However if you really need a queue, as opposed to a sorted collection, then the inbuilt PriorityQueue may be of use.
Not exactly answering your question, but with Java you may want to look into the built-in Collection classes. You can get priority queue behavior but using a TreeSet (a type of ordered-set) and implementing a custom Comparator for Patient instances. Depending what you're trying to achieve, this may be preferable. It would look something like this:
In Patient.java ...
class Patient implements Comparator {
...
public int compareTo(Patient other) {
return getPriority() > other.getPriority() ? 1 : 0;
}
Then in the place you want to use the queue
Set<Patient> queue = new TreeSet<Patient>();
queue.add(p1);
queue.add(p2);
//traverse in order of priority
for(Patient p : queue) {
doStuff();
}
Here is a simple implementation of a PriorityHeap. I coded it up pretty quick so it may have some flaws but I have implemented the pushUp() and pushDown() logic.
import java.util.Random;
public class Heap {
private Double[] data;
private int lastItem;
public Heap(int initialSize) {
// to simplify child/parent math leave the first index empty
// and use a lastItem that gives us the size
data = new Double[initialSize];
lastItem = 0;
}
public void insert(Double d) {
// double size if needed
// should have a matching shrink but this is example code
if (lastItem + 1 >= data.length) {
Double[] doubled = new Double[data.length * 2];
System.arraycopy(data, 0, doubled, 0, data.length);
data = doubled;
}
data[lastItem + 1] = d;
lastItem++;
pushUp(lastItem);
}
public void pushDown(int index) {
if (lastItem > 1) {
int leftChildIndex = index * 2;
int rightChildIndex = leftChildIndex + 1;
// assume that neither child will dominate (in priority)
// the item at index
int indexToPromote = index;
// there may not be a left child
if (leftChildIndex <= lastItem) {
Double leftChild = data[leftChildIndex];
Double tmp = data[index];
if (tmp.compareTo(leftChild) < 0) {
indexToPromote = leftChildIndex;
}
// there might not be a right child
if (rightChildIndex <= lastItem) {
Double rightChild = data[rightChildIndex];
tmp = data[indexToPromote];
if (tmp.compareTo(rightChild) < 0) {
indexToPromote = rightChildIndex;
}
}
}
// did either child dominate the item at index
// if so swap and push down again
if (indexToPromote != index) {
swap(index, indexToPromote);
pushDown(indexToPromote);
}
}
}
public void pushUp(int index) {
if (index > 1) {
// equivalent to floor((double)index/2.0d);
// if item at index is greater than its parent
// push the item up to until if finds a home
int parentIndex = index >>> 1;
Double parent = data[parentIndex];
Double item = data[index];
if (item.compareTo(parent) > 0) {
swap(parentIndex, index);
pushUp(parentIndex);
}
}
}
public Double removeTop() {
// assume size is zero then examine other cases
Double top = null;
if (lastItem > 1) {
// save the top item and take the bottom item and place it
// at the top the push the new top item down until it
// finds a home
top = data[1];
Double bottom = data[lastItem];
lastItem--;
data[1] = bottom;
pushDown(1);
} else if (lastItem == 1) {
top = data[1];
lastItem--;
}
return top;
}
public int size() {
return lastItem;
}
private void swap(int index1, int index2) {
Double temp = data[index1];
data[index1] = data[index2];
data[index2] = temp;
}
public static void main(String[] args) {
Heap heap = new Heap(4);
Random r = new Random();
for (int i = 0; i < 100000; i++) {
Double d = Double.valueOf(r.nextDouble() * 100.0d);
heap.insert(d);
}
double max = Double.MAX_VALUE;
while (heap.size() > 0) {
Double top = heap.removeTop();
if (top.doubleValue() > max) {
System.out.println("bad ordering...");
}
max = top.doubleValue();
System.out.println(max);
}
System.out.println("done...");
}
}