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.
Related
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.
I am trying to get a better understanding of the Models and their Nodehierarchy in Libgdx.
As much as i understood, a Model is made of many ChildNodes, which can contain other Nodes as well. Each node has a Vector3 translation describing its position, Vector3 scale, describing its scale and Quaternion rotation describing its rotation, all relative to the parent Node or Model. The Matrix4 gloabalTransform describes the same, but relative to the world they are in.
Now if i think about games like Garrys Mod, where the Models of the Players can move parts of the model dynamically (for example if they lie on an edge after they died their upper body can hang down the wall), i can only think about, that they modify the single Nodes at runtime, in their source code.
Now my questions:
Is my assumption correct?
Do i have the possibility to create the Nodes in Blender (lets say 1 Node is the left lower leg, 1 Node is the left upper leg...) and get and change them at runtime by using (for example) modelInstance.getNode("leftLowerLeg").translation.set(Vector3 position), or are they created and named automatically, depending on the shape, facecount...?
Thanks a lot!
Looking at that it appears that the concept of node is that of scene graph. Your model can be made of parts (MeshPart) and each separate part is a child of a node. Having a separate node means you can apply transforms to it thus moving it independently from any other model part. So it appears that you do want to construct your model as separate parts and load those parts in a hierarchy of nodes to suit your needs. Keep a reference to the node you want to move independently and apply transforms.
Node can "contain" a MeshPart (i.e. MeshPart is child of Node) Nodes can contain other nodes. take a look wikipedia for scene graph terminology. Hang on the docs for Model say "A model represents a 3D assets. It stores a hierarchy of nodes. A node has a transform and optionally a graphical part in form of a MeshPart and Material. Mesh parts reference subsets of vertices in one of the meshes of the model. Animations can be applied to nodes, to modify their transform (translation, rotation, scale) over time." Note it says sub set of vertices which implies that the model is one model but you separate them for your needs assigning different sub sets into Nodes.
From Xoppa:
This tutorial shows how to use the node hierarchy from the modeling application.
Here are two tutorials explaining the node structure and how to use it:
Theory
Practical
I am currently working on this exact problem. Nodes can have nodes which can have nodes! You can find a specific node using ModelInstance.getNode(String NameOfNode); which returns an object of type Node. These nodes are named what you named the objects in blender. EG, to get the Right shoulder bone in a model with the bone named Shoulder_R, you could do:
Node node = myModelInstance.getNode("Shoulder_R");
node that contains all the information pertaining to that bone, including translation, rotation, scale, and the appropriate transform matrices. I am currently stuck at the point of trying to manipulate these bones while an animation is playing, post the animation controller update.
My desired end result is to manually modify for example where an arm is pointing so its pointing at another object while the animation and model continue to play/move. I hope this helps you in your quest, and if you discover the answer to the remaining part of the mystery, please post back!
I need to generate a Voronoi diagram around a concave (non-convex) inside polygon. I have looked for methods online, but I haven't been able to figure out how to do this. Basically, I generate the convex hull of the points, calculate the dual points and build an edge network between these points. However, when meeting the edges of the inside polygon, it has to look like the edge of the shape, just like the convex hull. So, by doing this and clipping all the edges at the borders, I should end up with a Voronoi diagram that has nice edges to the borders of the inside polygon and no cells that are on both sides of the inside polygon.
Let me give you an example:
The problem with this is that the cells cross the inside polygon edges and there is no visual relation between the cell structure and the polygon shape.
Does anybody know how to approach this problem? Is there some algorithm that already does this or gets close to what I'm trying to achieve?
Thank you so much for any kind of input!
You might be able to build a conforming Delaunay triangulation (i.e. a triangulation that includes the polygon edges as constraints) and then form the Voronoi diagram as the dual. A conforming triangulation will ensure that no edge in the triangulation intersects with a constraint edge - all constraint edges will be an edge in the triangulation.
Have a look at the Triangle package here, as a reference for this type of approach. In my experience it's a fast and robust library, although it's written in c not java.
I'm not sure I understand at this stage how the points (the Voronoi centres) are generated in your diagram. If you're actually looking to do mesh generation in a polygonal domain, then there may be other approaches to consider, although the Triangle package supports (conforming) Delaunay refinement mesh generation.
EDIT: It looks like you can also directly form the Voronoi diagram for general line segments, check out the VRONI library, here. Addressing your comment - I'm not sure that you can always expect to have a uniform Voronoi diagram that also conforms to a general polygonal boundary. I would expect that the shape of the polygonal boundary would impose a maximum dimension on the boundary Voronoi cells.
Hope this helps.
Clearly you need to generate your Voronoi diagram to the constraints of the greater polygon. Although you refer to it as a polygon, I notice that your example diagram has spline-based edges. Let's forget that for now.
What you want to do is to ensure that you start out with the containing polygon (whether generated by you or from another source) having edges of fairly equal length; a variance factor would make this look more natural. I would probably go for a variance of 10-20%.
Now that you have your containing polygon bounded by lines segments of approximately equal length, you have a basis from which to begin generating your Voronoi diagram. For each edge on your container:
Determine the edge normal (perp line jutting inward from centre of that segment).
Use the edge normal as a sliding scale on which to place a new Voronoi node centre. The distance away from the edge itself would be determined by what you want your average Voronoi cell "diameter" to be, if they were all taken as circles. In your example that looks like maybe 30 pixels (or whatever the equivalent in your world units would be). Again, you should apply a variance factor to this so that not every cell centre is placed equidistant from its source edge.
Generate the Voronoi cell for your newly placed centre.
Store your Voronoi cell source point in a list.
As you incrementally generate each point, you should begin to see that the algorithm subdivides each convex "constituent area" of your concave container in a radial fashion.
You may be wondering what the list is for. Well, obviously, you're not done yet, you've only generated a fraction of the total Voronoi tesselation you want. Once you have created these "boundary" cells of your concave space, you don't want new cells to be generated closer to the boundary than the boundary cells already are, you only want them inside that area. By maintaining a list of the boundary cell source points, you can then ensure that any further points you create are inside that area. It's a little bit like taking an internal Minkowski sum to ensure you have a buffer zone. Now you can randomise the rest of your cells in this derived concave space, to completion.
(Caveat emptor: You will have to be careful with this previous step. If any "passage" areas are too narrow, then the boundaries of this derived space will overlap, you will have a non-simple polygon, and you may find yourself placing points in the wrong places in spite of your efforts. The solution is to ensure that either your maximum placement distance from edges is never more than half of your minimum passage width... or use some other geometric means, including Minkowski summation as one possibility, to ensure you do not wind up with a degenerate derived polygon. It is quite possible that you will end with a multipolygon, i.e. fragments.)
I've not applied this method myself yet, but although there will certainly be bugs to work out, I think the general idea will get you started in the right direction.
Look for a paper called:
"Efficient computation of continuous skeletons" by Kirkpatrick, David G, written in 1979.
Here's the abstract:
An O(n lgn) algorithm is presented for the construction of skeletons
of arbitrary n-line polygonal figures. This algorithm is based on an
O(n lgn) algorithm for the construction of generalized Voronoi
diagrams (our generalization replaces point sets by sets of line
segments constrained to intersect only at end points). The generalized
Voronoi diagram algorithm employs a linear time algorithm for the
merging of two arbitrary (standard) Voronoi diagrams.
"Sets of line segments is the constrained to intersect only at end points" is the concave polygon you describe.
I have a digraph graph G=(V,E) that I would like to redraw because it is currently very messy. This is a flow chart that is being visualized and since |V|>1000 and each v in V has more than 1 outgoing edge, it is very hard to trace by eye. For instance; a node on the lower left corner is connected by an edge to a node on the upper right corner. It would be better, for example, if these two nodes were placed next to each other. There are too many edges and it is a pain to trace each of them.
I have access to and can change the (x,y) coordinates of all the vertices. I would like to redraw G by maintaining it's current structure, in a way that is more human-friendly. I thought that minimizing the number of intersecting edges may be something to start with.
Is there an algorithm that can help me redraw this graph?
My question is, how do I assign (x,y) coordinates to each v in V such that it is organized better and easier to trace and read? How do I express these requirements formally? Should I go with a heuristic, if this is NP? Here is an example for a somewhat organized graph and this is something messy (although much smaller than what I'm dealing with).
Any help will be greatly appreciated. Thanks.
EDIT: I'm still looking for a to-the-point answer. I've researched into planar straight-line and orthogonal drawing methods but what I've got is lengthy research papers. What I'm seeking is an implementation, pseudo-code or at least something to get me started.
EDIT 2: I'm not trying to display the graph. The input to the algorithm shall be the graph G (composed of V and E) and the output shall be {(xi, yi) for each vi in V}
You want to look at graphviz.org; this is a difficult problem on which there has been a lot of research, reimplementing the wheel is not the right way to go.
Probably you'll have to get the java to write out a datafile which a tool like 'dot' can read and use for the graph layout.
That messy one seems to be drawn using spline, try planar straight line algorithm instead. Indeed this is a very difficult problem and I always use GraphViz as my backend graph drawing tools, you can generate that graph you want with -Gsplines=line option.
i would like to build a dynamic data structure that can hold a list of polygons and return a list of polygons that overlaps a specified rectangle.
i looked into bst trees (and quad trees) but these dont seem to work too well when the polygons overlap heavily.
any good ideas i should check out before i roll my own nonsense?
edit
lets assume all the polygons are normal non rotated rectangles. im willing to take the hit (point in polygon test) during point tests (i might be doing it anyway), and during a region test getting their bounding boxes is just as good. only a small percentage of them will actually not overlap the region in question.
I would look at 2-d segment delaunay graphs. Look also at Nef polygons. CGAL has a lot of set operations on polygons. Answers to this question may also be of value
Edit If your polygons are non rotated rectangles see R-Trees
Why do you write that yourself? Java offers complex intersection tests. You can convert your polygon data structures and your rectangle to Java.awt.geom.Area and then call the Area.intersect() method which does all the math for you.
It also takes care of all the rarely occurring (but still important) special cases which are really nasty to catch.
i just wrote a regular quadtree, that allowed each leaf node to hold unlimited polys, if the intersection of the bounds of the leaf and the bounds of each poly in the bucket were equivalent. otherwise leaf nodes are limited to 8 polys, before splitting.