cdc.graphs.impl.TreeAsGraph Maven / Gradle / Ivy
package cdc.graphs.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import cdc.graphs.EdgeDirection;
import cdc.graphs.EdgeTip;
import cdc.graphs.GraphAdapter;
import cdc.graphs.TreeAdapter;
import cdc.util.function.IterableUtils;
/**
* Graph adapter implementation over a TreeAdapter.
*
* This is used to build a filtered view of the underlying tree as a graph.
*
* @author Damien Carbonne
*
* @param Node class.
*/
public class TreeAsGraph implements GraphAdapter> {
private final TreeAdapter tree;
private final Set nodes = new HashSet<>();
private final Set> edges = new HashSet<>();
private final Map>> nodesToEdges = new HashMap<>();
private N root = null;
public TreeAsGraph(TreeAdapter tree) {
this.tree = tree;
}
public void setRoot(N root) {
this.root = root;
nodes.clear();
edges.clear();
nodesToEdges.clear();
if (root != null) {
build(root);
}
}
/**
* Returns the tree root seen by the graph.
*
* This is not necessarily the tree root.
*
* @return The tree root as seen by the graph.
*/
public final N getRoot() {
return root;
}
private void build(N node) {
nodes.add(node);
if (tree.hasChildren(node)) {
final Set> tmp = new HashSet<>();
for (final N child : tree.getChildren(node)) {
final BasicGraphEdge edge = new BasicGraphEdge<>(node, child);
edges.add(edge);
tmp.add(edge);
}
nodesToEdges.put(node, tmp);
}
}
@Override
public Iterable extends N> getNodes() {
return nodes;
}
@Override
public boolean containsNode(N node) {
return nodes.contains(node);
}
@Override
public Iterable extends BasicGraphEdge> getEdges() {
return edges;
}
@Override
public boolean containsEdge(BasicGraphEdge edge) {
return edges.contains(edge);
}
@Override
public Iterable extends BasicGraphEdge> getEdges(N node,
EdgeDirection direction) {
final Set> set = nodesToEdges.get(node);
if (direction == null) {
return set;
} else if (direction == EdgeDirection.INGOING) {
return IterableUtils.filter(set, new GraphEdgeIngoingPredicate<>(node));
} else {
return IterableUtils.filter(set, new GraphEdgeOutgoingPredicate<>(node));
}
}
@Override
public N getTip(BasicGraphEdge edge,
EdgeTip tip) {
return edge.getTip(tip);
}
}