OrientDB get label from vertex and get relationship from vertex - java

I have two separate questions:
How can I get the label of a vertex object.
I tried vertex.getId() .getClass() and similar but nothing is even close to the label I set to the vertex.
and, how can I get a relationship which connects any vertices of a set of vertices.
Iterable<Vertex> startNodes = getVertexList(relationshipStorage.getStartNode(), graph);
Iterable<Vertex> endNodes = getVertexList(relationshipStorage.getEndNode(), graph);
List<Edge> list = StreamSupport.stream(startNodes.spliterator(), false)
.flatMap(vertex1 -> StreamSupport.stream(vertex1.getEdges(Direction.OUT, relationshipId).spliterator(), false))
.filter(edge -> StreamSupport.stream(endNodes.spliterator(), false).anyMatch(vertex -> edge.getVertex(Direction.OUT).equals(vertex)))
.collect(Collectors.toList());
I am currently streaming through all the start vertices and looking if a relationship leaving them matches one of the end vertices.
Isn't there nothing more nicer?

You could use
vertex.getProperty("#class");
to get the name of the class of your vertex.

Related

Identifying disjoined graphs in JgraphT

I have a use case as below. I need to construct a graph from a set of input as below -
SimpleDirectedGraph<String, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class);
g.addVertex("APP");
g.addVertex("CHROME");
g.addVertex("MOZILLA");
g.addVertex("LAPTOP");
g.addVertex("SERVER");
g.addVertex("CHROME_DEV");
g.addVertex("MOZILLA_DEV");
g.addVertex("APP_DEV");
Add edges for Server
g.addEdge("SERVER", "APP");
g.addEdge("SERVER", "CHROME");
g.addEdge("SERVER", "MOZILLA");
Add edges for Laptop
g.addEdge("LAPTOP", "APP_DEV");
g.addEdge("LAPTOP", "CHROME_DEV");
g.addEdge("LAPTOP", "MOZILLA_DEV");
Add Connecting edges between these 2 sets
g.addEdge("CHROME", "CHROME_DEV");
g.addEdge("MOZILLA", "MOZILLA_DEV");
Now i can construct a graph like this and the structure will looks something as below -
But my use starts here. Imagine i have removed the connecting edges from the graph above
g.removeEdge("CHROME", "CHROME_DEV");
g.removeEdge("MOZILLA", "MOZILLA_DEV");
Now my graph is essentially disjoint from each other. How do I find out it is disjoint graphs and how to get both the disjoint graphs. I will have to treat these two disjoint graphs separately here after.
What you are looking for is called 'connected components'. Have a look at the ConnectivityInspector.
To test whether your graph is connected:
Graph<String, DefaultEdge> g = new SimpleDirectedGraph<>(DefaultEdge.class);
ConnectivityInspector ci = new ConnectivityInspector(g);
//Test whether the graph is connected:
ci.isConnected();
You can get the vertices of each of the connected components using:
Set<String> vertexSets = ci.connectedSets();
For each of these sets, you can then create a graph induced on these vertices:
Set<String> vertexSets = ci.connectedSets();
for(Set<String> vertexSet : vertexSets){
Graph<String, DefaultEdge> subgraph = new AsSubGraph(g,vertexSet);
//Do something with the subgraph
}
More information on graph connectivity can be found here. For the purpose of your question you could also look into the difference between 'strongly' and 'weakly' connected components.

Recursive method implementation problem with Spark

I have a graph with nodes to color, where for each node a dataset (a collection of rows / tuples) is associated.
The algorithm is explained by this example:
the uploaded figure shows an execution of Coloring over graph G with
nodes {v1, v3, v2}. Figure (a) initializes nodes as
uncolored. We first consider v1, and select Sσ1 = {{t9, t10}} (Figure (b)). We color nodes v2 and v3 by recursively calling Coloring.
Coloring one node may restrict the color choice of neighboring nodes,
e.g. after we select {{t9, t10}} for v1, we cannot select {{t6, t7,
t10}} for v3 due to the overlapping tuple t10. For node v3,
we have several choices including {{t6, t7}} and {{t7, t8}}. In Figure (c), we assume the coloring algorithm chooses {{t6, t7}} for
v3. As a result, {{t5, t6}}, which was the only choice forv2, cannot
be used due to the overlapping tuple t6. This leads the algorithm
towards an unsatisfying clustering (Figure (d)). The algorithm
backtracks its last decision for v3 by selecting a different color,
{{t7, t8}} for v3 in Figure (e). In this case, the clustering {{t5,
t6}} for v2 does not overlap with {{t7, t8}}. Since we have found a
clustering that satisfies all the constraints (i.e., a coloring of all nodes), Coloring returns true with V containing the nodes and their colors
(i.e., clusterings).
Here's my code i am trying (which i suspect it is wrong the way it colors the nodes because the algorithm runs for too long )
nodeIterator parameter contains all nodes of the graph sorted in customized way.
public Boolean coloring(graph, nodeIterator, vector){
Node nodeIt ;
if (nodeIterator.hasNext())
nodeIt = nodeIterator.next();
else {
return false;
}
// cluster is the current node associated dataset
ArrayList<Dataset<Row>> cluster = allClustersOfGraph.getNextDataset(nodeIt.name);
if (graph.getNeighbors(nodeIt) == null) {
if (!nodeIterator.hasNext()){
colorNode(vector, nodeIt);
return false;
}
else {
colorNode(vector, nodeIt);
nodeIterator.next();
}
}
Iterable<Node> adjNodes = graph.getNeighbors(nodeIt);
Iterator<Node> adjNodesIt = adjNodes.iterator();
// i suspect in the line under, while is an if so that next neighboring nodes of the current processed one, will be in turn processed in the next recursive call of this algorithm
while (adjNodesIt.hasNext()){
Node adjNode = adjNodesIt.next();
if (!checkNodeColored(vector, adjNode)) {
ArrayList<Dataset<Row>> adjCluster = allClustersOfGraph.getNextDataset(adjNode.name);
for (Dataset<Row> subCluster : cluster) {
for (Dataset<Row> subAdjCluster : adjCluster) {
// small datasets (tuples of rows) don't intersect
if (noDatasetIntersection(subCluster, subAdjCluster)) {
colorNode(vector, nodeIt, subCluster);
if (coloring(graph, nodeIterator, vector)) {
return true;
} else {
// vector is where current coloring progress is maintained
// move backwards
vector.remove(vector.size() - 1);
}
}
}
}
} else if (!adjNodesIt.hasNext()) {
// Color last node anyway
colorNode(vector, nodeIt);
return true;
}
}
return false;
}
allClustersOfGraph is of type ArrayList<ArrayList<Dataset<Row>>>
Here's also the pseudo-algorithm :
My question is : i created the loop while (adjNodesIt.hasNext()){...in my code to check for one recursive call all neighboring nodes of the current processed node, is it right to do that in a recursive method ? Also are all limit cases treated through my implementation ?
Thanks for the great help!

Converting a 2-3-4 tree into a red black tree

I'm trying to convert a 2-3-4 Tree into a Red-Black tree in java, but am having trouble figuring it out.
I've written these two basic classes as follows, to make the problem straightforward, but can't figure out where to go from here.
public class TwoThreeFour<K> {
public List<K> keys;
public List<TwoThreeFour<K>> children;
}
public class RedBlack<K> {
public K key;
public boolean isBlack;
public RedBlack<K> left,right;
public RedBlack<K key, boolean isBlack, RedBlack<K> left, RedBlack<K> right){
this.key = key; this.isBlack = isBlack; this.left = left; this.right = right;
}
}
I'm assuming the 2-3-4 tree is valid, and want to return a red black tree when the method is called.
I've also tried the following code with no luck:
public convert(TwoThreeFour<K> tTF){
if (ttf.keys.size() == 3)
RedBlack<K> node = RedBlack<ttf.keys[1], true, RedBlack<ttf.keys[0], false, /* not sure what to put here for left */, /* not sure what to put here for right */), RedBlack<ttf.keys[2], false, /* not sure what to put here for left */, /* not sure what to put here for right */)
etc. for keys.size() == 2, 1....
I know it has to be recursive in theory, but am having a hard time figuring it out. Any thoughts?
Consider these three rules:
Transform any 2-node in the 2-3-4 tree into a black node in the
red-black tree.
Transform any 3-node into a child node and a parent node. The
child node has two children of its own: either W and X or X and Y.
The parent has one other child: either Y or W. It doesn’t matter
which item becomes the child and which the parent. The child is
colored red and the parent is colored black.
Transform any 4-node into a parent and two children, the first
child has its own children W and X; the second child has children Y
and Z. As before, the children are colored red and the parent is
black.
The red-black rules are automatically satisfied if you follow these rules. Here's the resulting example tree after applying the transformations.
Hopefully that should get you going. For easy to understand and detailed explanation, you can refer to Robert Lafore's Data Structures book.

Drawing directed edges programmatically in Prefuse

I use the following code to display a graph:
graph = new Graph(true);
vis = new Visualization();
vis.add(GRAPH, graph);
CustomLabelRenderer re = new CustomLabelRenderer();
re.setImageField(NODE_TYPE_IMAGE);
re.setImagePosition(Constants.TOP);
EdgeRenderer edgeRenderer = new EdgeRenderer(Constants.EDGE_TYPE_LINE, Constants.EDGE_ARROW_FORWARD);
edgeRenderer.setArrowType(Constants.EDGE_ARROW_FORWARD);
edgeRenderer.setArrowHeadSize(10, 10);
DefaultRendererFactory factory = new DefaultRendererFactory(re, edgeRenderer);
factory.add(new InGroupPredicate(EDGE_DECORATORS), new LabelRenderer(VisualItem.LABEL));
vis.setRendererFactory(factory);
As you can see instantiate the graph to use directed edges. Afterwards I set the EdgeRenderer to use arrow heads. However, I can't see any arrows on my edges, but just plain lines. What am I doing wrong?
That's how I add edges:
graph.addEdge(node1, node2);
You need to set the FILLCOLOR for edges:
filter.add(new ColorAction(edges, VisualItem.FILLCOLOR,
ColorLib.rgb(100,100,100));
I reproduce the problem with the RadialGraphView demo and I did not need any changes to the source code except for this line. (Though, I had to change the data file.)

JTree drop index between nodes

I've implemented drag and drop in my JTree and it works, but I find this to be a bit confusing. In the picture, I'm showing how the drop location between item4 and item5 can vary depending on how far down between the nodes you are. I'm guessing this is because the row boundaries for item4 and item5 meet in the middle between them, and depending on which side you are on, you are actually in a different row.
From a user perspective, I think this is not natural. I would think that if I dropped above a node, the drop would occur above it. If I dropped below the node, the drop would occur below it. Is there a way to configure that sort of behavior?
EDIT: Adding code to show how to get drop location
DropLocation dropLoc = support.getDropLocation();
Point dropPoint = dropLoc.getDropPoint();
tree.getTree().getPathForLocation(dropPoint.x, dropPoint.y);
Note that support is a TransferSupport object
EDIT 2: I seemed to have solved this problem by checking if the drop point is above or below the halfway point of the node. Then I can tell if the drop was above or below which node.
You have sort out of the answer, but since i have sort out the code, thinking still worth to post it.
public void dragOver(DropTargetDragEvent dtde)
{
Point dropPoint = dtde.getLocation();
TreePath path = tree.getPathForLocation(dropPoint.x, dropPoint.y);
Rectangle pathBounds = tree.getPathBounds(path);
Rectangle topHalf = new Rectangle(pathBounds.x, pathBounds.y, pathBounds.width, pathBounds.height / 2);
if (topHalf.contains(dropPoint))
{
System.out.println("top half");
}
else
{
System.out.println("bottom half");
}
}

Categories

Resources