cdc.graphs.impl.ExtensionSubGraph Maven / Gradle / Ivy
package cdc.graphs.impl;
import java.util.HashSet;
import java.util.function.Predicate;
import cdc.graphs.EdgeDirection;
import cdc.graphs.EdgeTip;
import cdc.graphs.GraphAdapter;
import cdc.util.function.IterableUtils;
/**
* Explicit subgraph defined by extension.
*
* At creation time the subgraph is empty. Nodes and edges are then added and removed again.
*
* Nodes and edges of a subgraph should belong to delegate.
* This is checked when possible, but if delegate changes, this is not
* guaranteed.
*
* @author Damien Carbonne
*
* @param Node class
* @param Edge class
*/
public class ExtensionSubGraph extends ExplicitSubGraph {
/** Set of nodes. They must also belong to delegate. */
private final HashSet nodes = new HashSet<>();
/** Set of edges. They must also belong to delegate. */
final HashSet edges = new HashSet<>();
/**
* Predicate used to check whether an edge is contained or not in the
* subgraph.
*/
private final Predicate isOwnedEdge = edges::contains;
public ExtensionSubGraph(GraphAdapter delegate) {
super(delegate);
}
@Override
public final void clear() {
edges.clear();
nodes.clear();
}
@Override
public final boolean isEmpty() {
return nodes.isEmpty();
}
@Override
public final void addNode(N node) {
checkNodeValidity(node);
nodes.add(node);
}
@Override
public final void removeNode(N node) {
final boolean removed = nodes.remove(node);
if (removed) {
for (final E edge : delegate.getEdges(node)) {
removeEdge(edge);
}
}
}
@Override
public final void addEdge(E edge) {
checkEdgeValidity(edge);
if (!edges.contains(edge)) {
edges.add(edge);
addNode(delegate.getTip(edge, EdgeTip.SOURCE));
addNode(delegate.getTip(edge, EdgeTip.TARGET));
}
}
@Override
public final void removeEdge(E edge) {
edges.remove(edge);
}
@Override
public final void removeEdges(N source,
N target) {
for (final E edge : delegate.getEdges(source, EdgeDirection.OUTGOING)) {
final N tgt = delegate.getTip(edge, EdgeTip.TARGET);
if (target == tgt) {
edges.remove(edge);
}
}
}
@Override
public final Iterable getNodes() {
return nodes;
}
@Override
public final boolean containsNode(N node) {
return nodes.contains(node);
}
@Override
public final Iterable getEdges() {
return edges;
}
@Override
public final boolean containsEdge(E edge) {
return edges.contains(edge);
}
@Override
public final Iterable extends E> getEdges(N node,
EdgeDirection direction) {
return IterableUtils.filter(delegate.getEdges(node, direction), isOwnedEdge);
}
@Override
public final N getTip(E edge,
EdgeTip tip) {
return delegate.getTip(edge, tip);
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + getNodesCount() + " node(s) " + getEdgesCount() + " edge(s)";
}
}