My question is mainly about map representation and I would like your opinions.
Having a map represented by a bunch of roads and a connection between them - let's say road A is connected to B,C,D on one edge but there are only turns possible from A to C and D.
Let's say I represent this by a graph where each road is an edge and each road meeting/end is a vertex.
I want to run an A* or any other on such representation but... moving from node to node in the graph I strictly need to know where did I come from... I mean - from what direction. The next vertexes I can move to depend on the open turns that I have.
I can keep where I came from but I also want this to be as generic as possible and the simple graph solution doesn't provide me a knowledge where do I come from.
Could you please advice me how would you approach this one?
Thanks!
Represent each node as a bunch of nodes, one for each incoming road.
So let us have the following graph.
And let use the following rules:
If Came to B from A than we can only turn to D
If Came to B from C than we can only go to E
If Came to C from A than we can go to both B and D
If Came to C from E than we can only go to B
Than we have the following equivalent graph, now every node marked by original name and incoming road:
This is universal way that allow as to use any standard algorithm for directed graph in such situation. For some algorithms you may need to create fake source or initial and sink or goal nodes to handle that in such graph they can be represented as several nodes each, in current case we may need an additional node to describe behavior if we start from this nose, instead of coming from some other, but generally it is just original structure represented as classical graph.
Also we don't really need to split A, D or E if they always have the same behavior.
Related
Assume an undirected graph where edges have int values.
Example Graph:
A---B---C
|
D
Example Edge Values:
A,B : 1
B,C : 2
B,D : 2
I am writing a program that does the following: Given a node, return all edges in which the node is involved together with the associated value. For example: IN: B → OUT: (C,2), (D,2). Or IN: C → OUT: (B,2).
I am looking for an efficient data structure to do that. The problem is not derived from graph theory, I just used that to explain it. I am not interested in shortest paths etc., just this kind of data store.
The only thing I could quickly come up with:
HashMap<String,Tuple>
where
class Tuple{
String node;
int value;
}
I would then put each edge in this set twice, for example (pseudocode):
hm.add(A, new Tuple(B,1))
hm.add(B, new Tuple(A,1))
Is there a more efficient way to do this?
How about Guava’s ValueGraph?
https://github.com/google/guava/wiki/GraphsExplained
I have a project that is given on my Artificial Intelligence course. I need to implement Greedy Search algorithm for my program. Description of my project is:
Two text files called “tree.txt” and “heuristic.txt” are given. “tree.txt” will define the search tree where each line will contain a parent-child relation and a path cost between them. Each data will be seperated with a space.
e.g.
A B 5
A C 3
B D 6
The first character in the first line will be the Start node (A in here) and the goal node will be “G”.
“heuristic.txt” will define the heuristic, h(n), values. Each line will contain the heuristic value of each node. Each data will be seperated with a space.
e.g.
A 20
B 15
C 18
Output:
The program should give the solution path and the path cost from start node to goal.
Now my problem is that i am familiar with Greedy Search theoretically, but never implemented it practically in coding. I really dont know from where to start. We are free to develop our program in any language. Mostly, i have skills in Java and C#. If anybody can give me some ideas, or help me with any similar examples or tutorials. Any kind of help will be greatly appreciated. Sorry for so much writing. Thank you in advance:)))
I suggest this solution using python.
To implement the graph in your program use a simple python dictionary. Here's the code:
class Tree:
def _init_(self,dict,heuristic):
self.tree=tree
self.heuristic=heuristic
def getHeuristicValue(self,state)
value=self.heuristic.get(state)
return value
The constructor call is something like:
g = Graph({'A':{'B':5,'C':3},'B':{'D':6}},{'A':20,'B':15,'C':18})
The getHeuristic python function pass accepts a state as an argument and returns the value of the heuristic of this state.
To learn about python's dictionary class I suggest you read the tutorial
To implement the search algorithm with python you should implement this simple pseudocode:
function Tree-Search(initialNode,goalNode) returns a solution,or failure
frontier.push(initialNode) with the value of the function heuristic(initialNode.state)+the path cost to reaxh this node
while(frontier)
node<-frontier.pop()
if node.state==GoalNode.state
return node
expand node, adding the resulting nodes to the frontier
return None
For the frontier you must use a priority queue because you must pop the node with the lower value of g(n)+h(n) (where g(n) is the path cost to reach this node and h(n) is the value of the heuristic function).
To implement priority queue you should use a heap of the standard library heapq
The node is a data structure that must contain four components:
node.state:the state in the state space to which the node corresponds.
node.parent:the node in the search tree that generated this node.
node.action: the action that was applied to the parent to generated the node.
node.pathCost: is g(n),the cost of the path from the initial state to the node.
Lastly, for expanding the node, you can use this python function:
def actions(self,state):
'''return a tuple that contain the state child of state '''
return tuple(self.tree.get(state))
I suggest you to look this for your problem.
You can get the solution simply go back from the node.state that returns from the output of the algorithm while node.parent is not null that is your solution.
I hope this is useful for your project.
I have a system of nonlinear dynamics which I which to solve to optimality. I know how to do this in MATLAB, but I wish to implement this in JAVA. I'm for some reason lost in how to do it in Java.
What I have is following:
z(t) which returns states in a dynamic system.
z(t) = [state1(t),...,state10(t)]
The rate of change of this dynamic system is given by:
z'(t) = f(z(t),u(t),d(t)) = [dstate1(t)/dt,...,dstate10(t)/dt]
where u(t) and d(t) is some external variables that I know the value of.
In addition I have a function, lets denote that g(t) which is defined from a state variable:
g(t) = state4(t)/c1
where c1 is some constant.
Now I wish to solve the following unconstrained nonlinear system numerically:
g(t) - c2 = 0
f(z(t),u(t),0)= 0
where c2 is some constant. Above system can be seen as a simple f'(x) = 0 problem consisting of 11 equations and 1 unkowns and if I where supposed to solve this in MATLAB I would do following:
[output] = fsolve(#myDerivatives, someInitialGuess);
I am aware of the fact that JAVA doesn't come with any build-in solvers. So as I see it there are two options in solving the above mentioned problem:
Option 1: Do it my-self: I could use numerical methods as e.g. Gauss newton or similar to solve this system of nonlinear equations. However, I will start by using a java toolbox first, and then move to a numerical method afterwards.
Option 2: Solvers (e.g. commons optim) This solution is what I am would like to look into. I have been looking into this toolbox, however, I have failed to find an exact example of how to actually use the MultiVariateFunction evaluater and the numerical optimizer. Does any of you have any experience in doing so?
Please let me know if you have any ideas or suggestions for solving this problem.
Thanks!
Please compare what your original problem looks like:
A global optimization problem
minimize f(y)
is solved by looking for solutions of the derivatives system
0=grad f(y) or 0=df/dy (partial derivatives)
(the gradient is the column vector containing all partial derivatives), that is, you are computing the "flat" or horizontal points of f(y).
For optimization under constraints
minimize f(y,u) such that g(y,u)=0
one builds the Lagrangian functional
L(y,p,u) = f(y,u)+p*g(y,u) (scalar product)
and then compute the flat points of that system, that is
g(y,u)=0, dL/dy(y,p,u)=0, dL/du(y,p,u)=0
After that, as also in the global optimization case, you have to determine what the type of the flat point is, maximum, minimun or saddle point.
Optimal control problems have the structure (one of several equivalent variants)
minimize integral(0,T) f(t,y(t),u(t)) dt
such that y'(t)=g(t,y(t),u(t)), y(0)=y0 and h(T,y(T))=0
To solve it, one considers the Hamiltonian
H(t,y,p,u)=f(t,y,u)-p*g(t,y,u)
and obtained the transformed problem
y' = -dH/dp = g, (partial derivatives, gradient)
p' = dH/dy,
with boundary conditions
y(0)=y0, p(T)= something with dh/dy(T,y(T))
u(t) realizes the minimum in v -> H(t,y(t),p(t),v)
I am trying to develop an algorithm wherein I have a Location Class. In each class, I create a list of its adjacent Locations. I want to know, how can I get the shortest path from one Location to another. I am trying to look for different algorithms but it seems that they doesn't answer my problem.
For example, I have a point A and I want to go to point B,
A - - C - - H - - J
|
F- - K- -B
My idea for this is if B is in the List of adjacent locations of A, then that is the shortest path. If not, it should search the adjacent locations of the adjacent locations of A. But I do not know how to implement this in code or if it is a good algorithm. I also want to display A - C - F - K - B as the route for the shortest path. I am also developing this one on j2me so I am a bit limited on the java features that I can use.
If anyone can help me, it will be much appreciated. Thanks
You are on the right track. What you describe is the start of BFS. BFS is a shortest-path algorithm that is both optimal [finds the shortest path] and complete [always finds a path if one exist] for unweighted graph - so it is probably the right choice.
BFS works on graphs. In here your graph is G = (V,E) such that V = {all locations} [the nodes/vertices/locations] and E = {(u,v),(v,u) | u and v are neighbors} [the edges/links/neighbors]
The idea of BFS is simpilar to what you are suggesting: first check if the starting node is also the target. Then check if one of the neighbors of the starting node is the target, then search for their neighbors....
Regarding getting the actual path from BFS: have a look at this post.
The idea is to maintain a map - for each node [location] - the map will indicate how did you get there? which node discovered it? After the BFS finished - follow the map from target to source, and you get the actual path [reversed of course]. The link provided gives more details about this idea.
Your problem is known in the computing world as a graph search problem, looking for the shortest path between two nodes. Graphs here are not the x and y axis graphs from math, but Nodes (or Locations in your example) connected by edges.
Dijkstra's algorithm is the most commonly used to find the shortest path between two nodes, and for your use case it is simplified slightly because the edges in your scenario all have a weight (or cost) of one. An implementation of this is available in JGraphT, though I'm not sure how easy that is to include in a J2ME environment.
Have a look at the A* algorithm Dijkstra's pathfinding algorithm.
By independent nodes, I mean that the returned set can not contain nodes that are in immediate relations, parent and child cannot both be included. I tried to use Google, with no success. I don't think I have the right search words.
A link, any help would be very much appreciated. Just started on this now.
I need to return the actual set of independent nodes, not just the amount.
You can compute this recursive function with dynamic programming (memoization):
MaxSet(node) = 1 if "node" is a leaf
MaxSet(node) = Max(1 + Sum{ i=0..3: MaxSet(node.Grandchildren[i]) },
Sum{ i=0..1: MaxSet(node.Children[i]) })
The idea is, you can pick a node or choose not to pick it. If you pick it, you can't pick its direct children but you can pick the maximum set from its grandchildren. If you don't pick it, you can pick maximum set from the direct children.
If you need the set itself, you just have to store how you selected "Max" for each node. It's similar to the LCS algorithm.
This algorithm is O(n). It works on trees in general, not just binary trees.
I would take-and-remove all leaves first while marking their parents as not-to-take, then remove all leaves that are marked until no such leaves are left, then recurse until the tree is empty. I don't have a proof that this always produces the largest possible set, but I believe it should.
I've provided an answer to a question for the same problem, although the solution is in python, the explanation, algorithm, and test cases could be applicable.