lphystudio.core.layeredgraph.Layering Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lphy-studio Show documentation
Show all versions of lphy-studio Show documentation
The GUI for LPhy language.
The newest version!
package lphystudio.core.layeredgraph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public interface Layering {
void apply(List nodes);
class LongestPathFromSinks implements Layering {
@Override
public void apply(List nodes) {
for (LayeredNode node : nodes) {
node.setLayer(0);
}
int[] minLayer = {0};
for (LayeredNode sink : getSinks(nodes)) {
traverseToSetLayers(sink, 0, minLayer);
}
for (LayeredNode node : nodes) {
node.setLayer(node.getLayer()-minLayer[0]);
}
}
private void traverseToSetLayers(LayeredNode node, int layer, int[] minLayer) {
if (node.getLayer() > layer) {
node.setLayer(layer);
if (layer < minLayer[0]) {
minLayer[0] = layer;
}
}
for (LayeredNode child : node.getPredecessors()) {
traverseToSetLayers(child, layer - 1, minLayer);
}
}
public String toString() {
return "From Sinks";
}
}
class LongestPathFromSources implements Layering {
int MAX_LAYERS = 20;
@Override
public void apply(List layeredNodes) {
List nodes = new LinkedList<>();
nodes.addAll(layeredNodes);
List predecessors = getSources(nodes);
nodes.removeAll(predecessors); // nodes now contains only nodes that are not roots;
setLayer(predecessors, 0);
for (int layerIndex = 1; !nodes.isEmpty(); layerIndex++) {
if (layerIndex > MAX_LAYERS)
throw new RuntimeException(
"Graphical tree exceeds maximum depth of " + MAX_LAYERS
+ "! (Graph not directed? Cycles?)");
List layer = new ArrayList<>();
for (LayeredNode item : nodes) {
if (predecessors.containsAll(item.getPredecessors()))
layer.add(item);
}
nodes.removeAll(layer);
predecessors.addAll(layer);
setLayer(layer, layerIndex);
}
}
public String toString() {
return "From Sources";
}
}
static List getSinks(List nodes) {
List sinks = new ArrayList<>();
for (LayeredNode node : nodes) {
if (node.isSink()) {
sinks.add(node);
}
}
return sinks;
}
/**
* @param nodes
* @return the nodes that have no incoming edges
*/
static List getSources(List nodes) {
List sources = new ArrayList<>();
for (LayeredNode node : nodes) {
if (node.isSource()) {
sources.add(node);
}
}
return sources;
}
static void setLayer(List nodes, int layer) {
for (LayeredNode node : nodes) {
node.setLayer(layer);
}
}
}