Jgraph: General Traversal & Forest Traversal - java

Good morning/afternoon/evening.
So our data structures course gave us an assignment to segment a grayscale image in java using the following algorithm:
Input: A gray-scale image with P pixels and number R
Output: An image segmented into R regions
1. Map the image onto a primal weighted graph.
2. Find an MST of the graph.
3. Cut the MST at the R – 1 most costly edges.
4. Assign the average tree vertex weight to each vertex in each tree in the forest
5. Map the partition onto a segmentation image
The thing is, they just threw us in the dark. They gave us the jgraph package which we had absolutely no experience with (we never studied it) practically saying "go teach yourselves". Nothing new there.
The way I'm going about doing this is by making a class for vertix objects that contains the coordinates of the pixel in addition to its value so that I can add each one both to the graph and a 2D array. Afterwards, I used the array to add weighted edges between adjacent vertices because java can't tell where in the graph a vertix actually is without edges.
Afterwards, I used Kruskal's packaged method for minimum spanning trees and an arraylist to get around the protected status of edge weights in the tree like so:
ArrayList<WeightedEdge> edgeList = new ArrayList<>(height*width*3);
KruskalMinimumSpanningTree mst4 = new KruskalMinimumSpanningTree(map4);
Set<DefaultWeightedEdge> edges = mst4.getSpanningTree().getEdges();
for (DefaultWeightedEdge edge : edges) {
edgeList.add(new WeightedEdge(edge, map4.getEdgeWeight(edge)));
}
edgeList.sort(null);
for (int i = 0; i < n; i++) {
map4.removeEdge(edgeList.get(edgeList.size()-1).getEdge());
}
So now that I cut the (R-1) most costly edges in the graph, I should be left with a forest. And that's where I hit another dead end. How do I get the program to traverse each tree? The way I'm understanding this, I need a general traversal algorithm to visit every tree and assign the average value to each vertix. The problem? There isn't a general traversal algorithm in the package. And there isn't a way to identify individual trees either.
The idea is easy to understand and implement on paper, really. The problems only lie in actually coding all of this in java.
Sorry if this was messy or too long, but I'm just at my wit's end and physical limits. Thank you in advance.

I am a big fan of JGraphT and honestly I think it is pretty good that you're given it for your task assignment. It takes a bit of time to get started, but then it proves to be a very good tool. But you also need to understand the CS behind implemented algorithms, using JGraphT without knowing the theory is somewhat difficult.
From your task assignment I don't really understand step 1 (building the primal weighted graph). The rest should work with JGraphT quite well.
You did step 2 with KruskalMinimumSpanningTree. Now you can sort the edges by weight and remove R-1 top edges from the graph.
I would, however, suggest that you first build a new graph which would represent the calculated MST. And then remove remove R-1 top edges from that graph. Effectively truning it into a forest.
How do I get the program to traverse each tree?
With the forest from the previous step you can use the ConnectivityInspector to get a list of sets of connected vertices. Each set will contain vertices from one of the trees of the forest. Sets of vertices are easy to work with, you don't need any traversal, just iterate over the set.

Related

Splitting a polygon into parts

In my application I work with OpenGL and large arrays of data.
One of the things I need to do is I receive multiple "simple" polygons that can be either convex or concave. By simply I mean geometrical definition - polygons without holes and intersecting edges.
I receive this poligons in the form of linked loop of points (vertices), where each Vi is connected to Vi-1 and Vi+1 points and nothing else. The last point is also connected to the first, giving us a loop as a result.
I will say right now that I figured out polygon triangulation, and it works like a charm (I used ear-clipping method for now).
But, I need to build LOTS of those polygons, millions of them. To minimize the load I decided to split my world into "chunks", squares like in Minecraft. I then use frustum culling and other optimizations methods to either render or discard/simplify these chunks and meshes in them.
So, what I want to do is: if the polygon I received lies in several different chunks - then I want to split it into meshes for each of those chunks. Basically, I want to create multiple polygons that are divided on chunk borders, and THEN triangulate them and create meshes for rendering.
As a result I want to have one (or several) contours that I can then triangulate.
here's a picture of my task:
I made an algorythm for splitting it myself that I thought would work, but I found that it only works if the contour in any given chunk doesn't break up, like you see in the example (in other words if there's only one figure in any given chunk).
I thought to ask here if anyone knows any good algorythms for that task? I'll probably come up with something myself, but practice shows that there's almost always a better and simpler ready-made solution out there. I'd really appreciated it if someone could give me a useful link or an article, if not with a solution itself, then something that could give ideas.
I'm not at work at the moment, because it's weekend, so I'll be trying/testing the things on Monday.
What I came up with at the moment, however, is a very simple solution.
test all points in the contour.
If point i and point i+1 don't belong to the same chunk (which I can test easily):
then find an intersection between chunk border and the line made by these two points.
add this new point to the contour between the original two points.
When every edge of the polygon was tested like that - triangulate it.
because we have points on the edges of the chunks - then during triangulation the triangles will fit exactly into chunk borders
for each triangle, decide which chunk it belongs to and generate the mesh in THAT chunk.
I won't go into details of some optimization ideas - like not needing to evaluate resulting triangles if the entire figure fits within the same chunk.
This is a stab in the dark at writing some pseudo code that may work. Feel free to implement it and select your own answer with the actual code if it works.
First, convert your vertex array to a double linked list that loops from the last element to the first element. Or it may be better to model it as an undirected graph instead, because a point may have missing neighbours.
Then apply the algorithm below for each quadrant, starting with the full polygon each time. You can cut down the size of that polygon by culling vertices that are outside of the quadrant and at least 1-neighbour away from edges that cross the cutting lines.
// We need to keep track of the points that we insert on the cutting lines
let LIX = List of X-Cut-Line Intersection Points
let LIY = List of Y-Cut-Line Intersection Points
foreach Edge AB in Poly where A is inside the quadrant, B outside
// Insert points into the polygon that intersect the X-Cut-Line
if AB Intersects X-Cut-Line
let Ix = Intersection Point
Insert Ix between AB so that A<->B becomes A<->Ix
B can be removed from the polygon now
Add Ix to LIX
// Insert points into the polygon that intersect the Y-Cut-Line
if AB.Intersects Y-Cut-Line
let Iy = Intersection Point
Insert Iy between AB so that A<->B becomes A<->Iy
B can be removed from the polygon now
Add Iy to LIY
// Then iterate pairs of points along each cutting line to join them
sort LIX by X Ascending
while (LIX.Length > 0)
let P0 = LIX[0]
let P1 = LIX[1]
Link P0 and P1
Remove P0 and P1 from LIX
sort LIY by Y Ascending
while (LIY.Length > 0)
let P0 = LIY[0]
let P1 = LIY[1]
Link P0 and P1
Remove P0 and P1 from LIY
Finally, you can look for cycles in the resulting linked list/graph to find the new polygons. Each cycle should in theory not contain points from the other cycles already detected so it is an individual polygon.

Look up the shape which contains an X,Y coordinate

I have a collection of java.awt.Shape objects covering a two-dimensional plane with no overlap. These are from a data set of U.S. Counties, at a fairly low resolution. For an (x,y) latitude/longitude point, I want a quick way to identify the shape which county contains that point. What's an optimal way to index this?
Brute force would look like:
for (Shape eachShape : countyShapes) {
if (eachShape.contains(x, y)) {
return eachShape;
}
}
To optimize this, I can store the min/max bounds of the (possibly complex) shapes, and only call contains(x, y) on shapes whose rectangular bounds encompass a given x,y coordinate. What's the best way to build this index? A SortedMultiset would work for indexing on the x minima and maxima, but how to also include the y coordinates in the index?
For this specific implementation, doing a few seconds of up-front work to index the shapes is not a problem.
If possible you could try a bitmap with each shape in a different color. Then simply query the point and the color and lookup the shape.
This question is outside the scope of Stackoverflow but the answer is probably Binary Space Partitioning.
Roughly:
Divide the space in two either on the x coordinate or y coordinate using the mid-point of the range.
Create a list of counties on the two sides of that line (and divided by that line).
On each side of that line divide the collections again by the other dimension.
Continue recursively building a tree dividing alternately by x and y until you reach a satisfactory set of objects to examine by brute force.
The conventional algorithm actually divides the shapes lying across the boundary but that might not be necessary here.
A smart implementation might look for the most efficient line to divide on which is the one where the longest of the two lists is the smallest.
That involves more up front calculation but a more efficient and consistently performing partition.
You could use an existing GIS library like GeoTools and then all the hard work is already done.
Simply load your shapefile of counties and execute queries like
"the_geom" contains 'POINT(x y)
The quickstart tutorial will show you how to load the shapes, and the query tutorial will show you how to query them.
Having min an max values of coordinates of the bounds not guarantee that you can determine if one point is in or out in any situations. If you want achieve this by yourself you should implement some algorithm. There's a good one that is called "radial algorithm", I recommend that uses this, and it isn't so complicated to implement, there are sufficient bibliography and examples.
Hope this help.

Minimax / Alpha Beta for Android Reversi Game

I have to implement a Reversi game for Android. I have managed to implement all the game, is functional, but the problem is that I don't have an AI. In fact, at every move the computer moves in the position that achieves him the highest number of pieces.
I decided to implement and alpha-beta pruning algorithm. I did a lot of research on the internet about it, but I couldn't come to a final conclusion how to do it. I tried to implement a few functions, but I couldn't achieve the desired behaviour.
My board is stored in class Board (inside this class, the pieces occupied by each player are stored in a bi-dimensional int array). I have attached an small diagram (sorry about the way it looks).
DIAGRAM: https://docs.google.com/file/d/0Bzv8B0L32Z8lSUhKNjdXaWsza0E/edit
I need help to figure out how to use the minimax algorithm with my implementation.
What I understood so far, is that I have to make an evaluation function regarding the value of the board.
To calculate the value of the board I have to account the following elements:
-free corners (my question is that I have to take care only about the free corners, or the one that I can take at the current move?! dilemma here).
-mobility of the board: to check the number of pieces that will be available to move, after the current move.
-stability of the board… I know it means the number of pieces that can't be flipped on the board.
-the number of pieces the move will offer me
I have in plan to implement a new Class BoardAI that will take as an argument my Board object and the dept.
Can you please tell me a logical flow of ideas how I should implement this AI?
I need some help about the recursion while calculating in dept and I don't understand how it calculates the best choice.
Thank you!
First you can check this piece of code for a checkers AI that I wrote years ago. The interesting part is the last function (alphabeta). (It's in python but I think you can look at that like pseudocode).
Obviously I cannot teach you all the alpha/beta theory cause it can be a little tricky, but maybe I can give you some practical tips.
Evaluation Function
This is one of the key points for a good min/max alpha/beta algorithm (and for any other informed search algorithm). Write a good heuristic function is the artistic part in AI development. You have to know well the game, talk with expert game player to understand which board features are important to answer the question: How good is this position for player X?
You have already indicated some good features like mobility, stability and free corners. However note that the evaluation function has to be fast cause it will be called a lot of times.
A basic evaluation function is
H = f1 * w1 + f2 * w2 + ... + fn * wn
where f is a feature score (for example the number of free corners) and w is a corresponding weight that say how much the feature f is important in the total score.
There is only one way to find weights value: experience and experiments. ;)
The Basic Algorithm
Now you can start with the algorithm. The first step is understand game tree navigation. In my AI I've just used the principal board like a blackboard where the AI can try the moves.
For example we start with board in a certain configuration B1.
Step 1: get all the available moves. You have to find all the applicable moves to B1 for a given player. In my code this is done by self.board.all_move(player). It returns a list of moves.
Step 2: apply the move and start recursion. Assume that the function has returned three moves (M1, M2, M3).
Take the first moves M1 and apply it to obtain a new board configuration B11.
Apply recursively the algorithm on the new configuration (find all the moves applicable in B11, apply them, recursion on the result, ...)
Undo the move to restore the B1 configuration.
Take the next moves M2 and apply it to obtain a new board configuration B12.
And so on.
NOTE: The step 3 can be done only if all the moves are reversible. Otherwise you have to find another solution like allocate a new board for each moves.
In code:
for mov in moves :
self.board.apply_action(mov)
v = max(v, self.alphabeta(alpha, beta, level - 1, self._switch_player(player), weights))
self.board.undo_last()
Step 3: stop the recursion. This three is very deep so you have to put a search limit to the algorithm. A simple way is to stop the iteration after n levels. For example I start with B1, max_level=2 and current_level=max_level.
From B1 (current_level 2) I apply, for example, the M1 move to obtain B11.
From B11 (current_level 1) I apple, for example, the M2 move to obtain B112.
B122 is a "current_level 0" board configuration so I stop recursion. I return the evaluation function value applied to B122 and I come back to level 1.
In code:
if level == 0 :
value = self.board.board_score(weights)
return value
Now... standard algorithm pseudocode returns the value of the best leaf value. Bu I want to know which move bring me to the best leaf! To do this you have to find a way to map leaf value to moves. For example you can save moves sequences: starting from B1, the sequence (M1 M2 M3) bring the player in the board B123 with value -1; the sequence (M1 M2 M2) bring the player in the board B122 with value 2; and so on... Then you can simply select the move that brings the AI to the best position.
I hope this can be helpful.
EDIT: Some notes on alpha-beta. Alpha-Beta algorithm is hard to explain without graphical examples. For this reason I want to link one of the most detailed alpha-beta pruning explanation I've ever found: this one. I think I cannot really do better than that. :)
The key point is: Alpha-beta pruning adds to MIN-MAX two bounds to the nodes. This bounds can be used to decide if a sub-tree should be expanded or not.
This bounds are:
Alpha: the maximum lower bound of possible solutions.
Beta: the minimum upper bound of possible solutions.
If, during the computation, we find a situation in which Beta < Alpha we can stop computation for that sub-tree.
Obviously check the previous link to understand how it works. ;)

How to draw a tree in java language

I am trying to parse an XML file in java, after I have to represent it as a tree using Jframe like this
Trees are generally one of the easier linked constructs to lay out like this, because paths generally don't "merge" or "cross".
You can approach it in a roughly tabular way by traversing the tree "left to right": start at the root, and draw its representation at the top left of the area. Then, traverse its "left" branch one level at a time, drawing those nodes' representations on successively lower "rows", in the same "column" as the root. Then, as you move to the "right"-side nodes, draw that node in the next "column" available to the right on the same level. This will produce a ramp-shaped graph of the tree's structure.
You can add some pre-analysis of the number of levels and nodes at each level, which will allow you to "center" the tree into a rough pyramid shape by knowing the maximum number of levels the graph will require and the number of nodes at each level of that graph. But, that requires traversing the entire graph before you start drawing anything.
As for "arranging" a tree's nodes so they fit in the smallest area without arrows crossing or overlapping, that's a problem with a scope far exceeding the average SO answer.
There are lots of good libraries for visualizing graphs.
Here's a pretty extensive list of options: http://s6ai.livejournal.com/33969.html
Us the standard forms to print the image
http://www.java-forums.org/awt-swing/6763-how-display-image.html
Prefuse could probably create something aesthetically similar. Of course, you could go the primitive route and do the graphics manually. For an XML to graph transform, the TreeMLReader API may be of some use, however you might have to convert the XML to the TreeML format with XSLT first.

minimum spanning tree out of adjacency matrix

I have a problem that I am really struggling with. I have a set of points with weighed edges and I need to create a minimum spanning tree to find the shortest amount of edges needed. I need to do it in java. Right now I have it creating an adjacency matrix and thats the point im stuck. I really have no idea where to go next. Any help would be awesome.
Take a look on Kruskal and Prim algorithms,
I really like Prim because it is very simple to implement and understand: http://en.wikipedia.org/wiki/Prim%27s_algorithm
About your question, what do next (Resumed Prim's algorithm):
Choose one random vertex and get the edge with smaller cost, insert it into your MST.
While you do not have all vertex at your MST:
Choose the edge with smaller cost frm the edges of your MST and insert it at your MST.
If you are trying to find a minimum spanning tree, you will always have the same number of edges, the weights will just be different. The method that I recommend using to solve this problem is Prim's algorithm. It works best when you have distinct weighted edges. Even though someone else has discussed it as a possibility, I will explain it in full here to solve the minimum spanning tree problem with an undirected, connected graph.
The first step to Prim's is starting with any vertex V and add it to a (currently) empty set of vertices called "Discovered". From there, you will look at all of the edges that are adjacent to V (using your adjacency matrix) and are connected to vertices that are not in "Discovered" (using your Discovered set), and add them to a minimum heap structure. The heap will allow you to take the minimum edge and add it to a new tree structure. The other end of that edge is your next new starting vertex. Repeat this process until you have your minimum spanning tree.

Categories

Resources