本文整理汇总了Java中org.jgrapht.traverse.TopologicalOrderIterator类的典型用法代码示例。如果您正苦于以下问题:Java TopologicalOrderIterator类的具体用法?Java TopologicalOrderIterator怎么用?Java TopologicalOrderIterator使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
TopologicalOrderIterator类属于org.jgrapht.traverse包,在下文中一共展示了TopologicalOrderIterator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getParameterOrdering
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private List<Field> getParameterOrdering(DirectedGraph<Field, DefaultEdge> dependencyGraph) {
CycleDetector<Field, DefaultEdge> cycleDetector = new CycleDetector<Field, DefaultEdge>(dependencyGraph);
if (cycleDetector.detectCycles()) {
throw new RuntimeException("Cyclic dependency detected!");
} else {
TopologicalOrderIterator<Field, DefaultEdge> orderIterator;
Field f;
orderIterator = new TopologicalOrderIterator<Field, DefaultEdge>(dependencyGraph);
List<Field> output = new ArrayList<>(dependencyGraph.vertexSet().size());
while (orderIterator.hasNext()) {
f = orderIterator.next();
output.add(f);
}
return output;
}
}
示例2: getSpeciesInHierarchicalOrder
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private Iterable<SpeciesDescription> getSpeciesInHierarchicalOrder(final ModelDescription model) {
final DirectedGraph<SpeciesDescription, Object> hierarchy = new SimpleDirectedGraph<>(Object.class);
final DescriptionVisitor visitor = new DescriptionVisitor<SpeciesDescription>() {
@Override
public boolean visit(final SpeciesDescription desc) {
if (desc instanceof ModelDescription)
return true;
final SpeciesDescription sd = desc.getParent();
if (sd == null || sd == desc)
return false;
hierarchy.addVertex(desc);
if (!sd.isBuiltIn()) {
hierarchy.addVertex(sd);
hierarchy.addEdge(sd, desc);
}
return true;
}
};
model.visitAllSpecies(visitor);
return () -> new TopologicalOrderIterator<>(hierarchy);
}
示例3: sort
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
public List<String> sort(List<Class<?>> classes) throws OrderSortCycleException {
List<String> result = new ArrayList<>();
SimpleDirectedGraph<String, DefaultEdge> graph = new SimpleDirectedGraph<>(DefaultEdge.class);
for (OrderConstraint orderConstraint : getConstraints(classes)) {
graph.addVertex(orderConstraint.getFirst());
graph.addVertex(orderConstraint.getSecond());
graph.addEdge(orderConstraint.getFirst(), orderConstraint.getSecond());
}
CycleDetector<String, DefaultEdge> cycleDetector = new CycleDetector<>(graph);
if(!cycleDetector.detectCycles()) {
for (TopologicalOrderIterator<String, DefaultEdge> iterator = new TopologicalOrderIterator<>(graph); iterator.hasNext();) {
result.add(iterator.next());
}
} else {
String cycles = Joiner.on(", ").join(cycleDetector.findCycles());
throw new OrderSortCycleException("The given order constraints contain (at least one) cycle. Cycles can only "
+ "be caused by static references because we have single inherintance only in Java (involved classes: '" + cycles + "').");
}
return result;
}
示例4: build
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private void build(Task task, ImmutableList.Builder<RunnableTaskDag> entriesBuilder, ImmutableMap.Builder<TaskId, Task> tasksBuilder)
{
DefaultDirectedGraph<TaskId, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);
worker(graph, task, null, tasksBuilder, Sets.newHashSet());
CycleDetector<TaskId, DefaultEdge> cycleDetector = new CycleDetector<>(graph);
if ( cycleDetector.detectCycles() )
{
throw new RuntimeException("The Task DAG contains cycles: " + task);
}
TopologicalOrderIterator<TaskId, DefaultEdge> orderIterator = new TopologicalOrderIterator<>(graph);
while ( orderIterator.hasNext() )
{
TaskId taskId = orderIterator.next();
Set<DefaultEdge> taskIdEdges = graph.edgesOf(taskId);
Set<TaskId> processed = taskIdEdges
.stream()
.map(graph::getEdgeSource)
.filter(edge -> !edge.equals(taskId) && !edge.getId().equals(""))
.collect(Collectors.toSet());
entriesBuilder.add(new RunnableTaskDag(taskId, processed));
}
}
示例5: sortChanges
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
/**
* Sorts the graph to provide a consistent topological ordering.
*
* @param graph The input graph - all vertices in the graph will be returned in the output list
* @param comparator The comparator on which to order the vertices to guarantee a consistent topological ordering
*/
public <T> ImmutableList<T> sortChanges(final DirectedGraph<T, DefaultEdge> graph, Comparator<? super T> comparator) {
if (graph.vertexSet().isEmpty()) {
return Lists.immutable.empty();
}
GraphUtil.validateNoCycles(graph);
TopologicalOrderIterator<T, DefaultEdge> iterator = getTopologicalOrderIterator(graph, comparator);
return Lists.immutable.withAll(IteratorUtils.toList(iterator));
}
示例6: orderDag
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private List<Handler<? extends Intent<? extends Resolution>>> orderDag(DirectedAcyclicGraph<Handler<? extends Intent<? extends Resolution>>, DefaultEdge> dag)
{
TopologicalOrderIterator<Handler<? extends Intent<? extends Resolution>>, DefaultEdge> topOrder = new TopologicalOrderIterator<>(dag);
List<Handler<? extends Intent<? extends Resolution>>> ordered = new ArrayList<>();
while(topOrder.hasNext()) {
Handler<? extends Intent<? extends Resolution>> handler = topOrder.next();
ordered.add(handler);
logger.debug("Added [{}] to ordered handler list", handler);
}
return ordered;
}
示例7: testCycleDetection
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
public void testCycleDetection() {
DefaultDirectedGraph<String, Object> g = new DefaultDirectedGraph<String, Object>(Object.class);
// Add vertices, e.g. equations.
g.addVertex("A");
g.addVertex("B");
g.addEdge("A", "B");
g.addVertex("D");
g.addVertex("A");
g.addEdge("D", "A");
g.addVertex("B");
g.addVertex("C");
g.addEdge("B", "C");
g.addVertex("G");
g.addVertex("H");
g.addEdge("G", "H");
g.addVertex("C");
g.addVertex("D");
g.addEdge("C", "D");
System.out.println(g.toString());
// Are there cycles in the dependencies.
CycleDetector<String, Object> cycleDetector = new CycleDetector<String, Object>(g);
// Cycle(s) detected.
if (cycleDetector.detectCycles()) {
System.out.println("Cycles detected.");
// Get all vertices involved in cycles.
Set<String> cycleVertices = cycleDetector.findCycles();
// Loop through vertices trying to find disjoint cycles.
while (!cycleVertices.isEmpty()) {
System.out.println("Cycle:");
// Get a vertex involved in a cycle.
Iterator<String> iterator = cycleVertices.iterator();
String cycle = iterator.next();
// Get all vertices involved with this vertex.
Set<String> subCycle = cycleDetector.findCyclesContainingVertex(cycle);
for (String sub : subCycle) {
System.out.println(" " + sub);
// Remove vertex so that this cycle is not encountered
// again.
cycleVertices.remove(sub);
}
}
}
// No cycles. Just output properly ordered vertices.
else {
TopologicalOrderIterator<String, Object> orderIterator = new TopologicalOrderIterator<String, Object>(g);
System.out.println("\nOrdering:");
while (orderIterator.hasNext()) {
String v = orderIterator.next();
System.out.println(v);
}
}
}
示例8: fillCache
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private static void fillCache(Class<? extends EObject> clazz, IProcessorCache cache, RegistryFunction fn) {
Set<IAtomicDerivedStateProcessor<? extends EObject>> processors = ClassUtils.getAllInterfaces(clazz).stream()
.filter(EObject.class::isAssignableFrom).map(fn::apply).filter(Optional::isPresent).map(Optional::get)
.collect(Collectors.toSet());
DirectedGraph<IAtomicDerivedStateProcessor<? extends EObject>, DefaultEdge> graph = new DirectedAcyclicGraph<>(
DefaultEdge.class);
processors.forEach(graph::addVertex);
processors.forEach(p -> addRequirements(p, fn, graph));
processors.forEach(i -> i.getReplacements().stream().map(fn::apply).filter(Optional::isPresent)
.map(Optional::get).forEach(r -> replaceVertex(graph, r, i)));
CycleDetector<?, ?> cycleDetector = new CycleDetector<>(graph);
if (cycleDetector.detectCycles()) {
IllegalStateException ex = new IllegalStateException(String.format(
"The state initializers for element type %s have cyclic dependencies.", clazz.getSimpleName()));
LOGGER.error(ex.getMessage(), ex);
throw ex;
}
TopologicalOrderIterator<IAtomicDerivedStateProcessor<? extends EObject>, DefaultEdge> iter = new TopologicalOrderIterator<>(
graph);
List<IAtomicDerivedStateProcessor<EObject>> orderedProcessors = new ArrayList<>();
iter.forEachRemaining(processor -> orderedProcessors.add((IAtomicDerivedStateProcessor<EObject>) processor));
Collections.reverse(orderedProcessors);
cache.put(clazz, orderedProcessors);
}
示例9: createGroup
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
protected Group createGroup(Deployment deployment) {
ArchiveRoot ar = toscaService
.prepareTemplate(deployment.getTemplate(), deployment.getParameters());
Map<String, NodeTemplate> nodes = Optional
.ofNullable(ar.getTopology())
.map(Topology::getNodeTemplates)
.orElseGet(HashMap::new);
// don't check for cycles, already validated at web-service time
DirectedMultigraph<NodeTemplate, RelationshipTemplate> graph =
toscaService.buildNodeGraph(nodes, false);
TopologicalOrderIterator<NodeTemplate, RelationshipTemplate> orderIterator =
new TopologicalOrderIterator<>(graph);
List<NodeTemplate> orderedMarathonApps = CommonUtils
.iteratorToStream(orderIterator)
.filter(node -> toscaService.isOfToscaType(node, ToscaConstants.Nodes.MARATHON))
.collect(Collectors.toList());
Group group = new Group();
List<App> apps = new ArrayList<>();
for (NodeTemplate marathonNode : orderedMarathonApps) {
MarathonApp marathonTask = buildTask(graph, marathonNode, marathonNode.getName());
List<Resource> resources = resourceRepository
.findByToscaNodeNameAndDeployment_id(marathonNode.getName(), deployment.getId());
resources.forEach(resource -> resource.setIaasId(marathonTask.getId()));
marathonTask.setInstances(resources.size());
App marathonApp = generateExternalTaskRepresentation(marathonTask);
apps.add(marathonApp);
}
group.setApps(apps);
return group;
}
示例10: orderClassesByHierarchy
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private List< Type > orderClassesByHierarchy( List< Type > classes )
{
DirectedGraph< Type, DefaultEdge > classHierarchyGraph = new DefaultDirectedGraph< Type, DefaultEdge >( DefaultEdge.class );
// Pass 1: add vertexes.
for ( Type aClass : classes )
classHierarchyGraph.addVertex( aClass );
// Pass 2: add edges.
for ( Type subClass : classes )
{
Type closestSuperClass = null;
for ( Type potentialSuperClass : classes )
{
if ( !potentialSuperClass.equals( subClass ) && isSubclass( potentialSuperClass, subClass ) )
{
if ( closestSuperClass == null || !isSubclass( potentialSuperClass, closestSuperClass ) )
closestSuperClass = potentialSuperClass;
}
}
if ( closestSuperClass != null )
classHierarchyGraph.addEdge( closestSuperClass, subClass );
}
TopologicalOrderIterator< Type, DefaultEdge > iter = new TopologicalOrderIterator< Type, DefaultEdge >( classHierarchyGraph );
List< Type > orderedClasses = new ArrayList< Type >();
while ( iter.hasNext() )
orderedClasses.add( iter.next() );
Collections.reverse( orderedClasses );
return orderedClasses;
}
示例11: getTopologicallyOrderedMappingConfigurations
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private List<MappingConfiguration> getTopologicallyOrderedMappingConfigurations(
JsonixContext context,
final List<ModuleConfiguration> moduleConfigurations) {
final DirectedGraph<MappingConfiguration, Object> mappingConfigurationDependencyGraph = buildMappingConfigurationDependencyGraph(
context, moduleConfigurations);
final StrongConnectivityInspector<MappingConfiguration, Object> strongConnectivityInspector = new StrongConnectivityInspector<MappingConfiguration, Object>(
mappingConfigurationDependencyGraph);
final List<Set<MappingConfiguration>> stronglyConnectedSets = strongConnectivityInspector
.stronglyConnectedSets();
for (Set<MappingConfiguration> stronglyConnectedSet : stronglyConnectedSets) {
if (stronglyConnectedSet.size() > 1) {
throw new IllegalArgumentException(MessageFormat.format(
"Mappings have the following dependency cycle: {0}",
stronglyConnectedSet.toString()));
}
}
final List<MappingConfiguration> mappingConfigurations = new ArrayList<MappingConfiguration>(
mappingConfigurationDependencyGraph.vertexSet().size());
for (Iterator<MappingConfiguration> mappingConfigurationsInTopologicalOrderIterator = new TopologicalOrderIterator<MappingConfiguration, Object>(
mappingConfigurationDependencyGraph); mappingConfigurationsInTopologicalOrderIterator
.hasNext();) {
mappingConfigurations
.add(mappingConfigurationsInTopologicalOrderIterator.next());
}
return mappingConfigurations;
}
示例12: topologicalSort
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
/**
* Sort a simple directed graph.
*/
@SuppressWarnings("boxing")
@Test
public void topologicalSort()
{
// Generate a small test graph
final DirectedGraph<Integer, DefaultEdge> g = directedGraph();
if (log.isDebugEnabled())
{
log.debug("Graph " + g);
}
// Topologically sort the graph
// this is a valid order; it is not unique but it seems that JGraphT generated the
// smallest-numbered available vertex first, so we can tell in advance what the
// expected values are.
final Integer[] expectedOrder =
{ 3, 5, 7, 8, 11, 2, 9, 10 };
final Iterator<Integer> iter = new TopologicalOrderIterator<>(
g);
int i = 0;
while (iter.hasNext())
{
final Integer next = iter.next();
if (log.isDebugEnabled())
{
log.debug(i + ": " + next);
}
assertEquals(expectedOrder[i], next);
++i;
}
}
示例13: getOrderedList
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
public List<Class> getOrderedList() {
List<Class> result = new ArrayList<Class>();
TopologicalOrderIterator<Class, DefaultEdge> orderIterator;
orderIterator = new TopologicalOrderIterator<Class, DefaultEdge>(g);
while (orderIterator.hasNext()) {
result.add(orderIterator.next());
}
return result;
}
示例14: testClassfication
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
@Test
public void testClassfication() {
Automaton a = new RegExp("az+g(at|yg)").toAutomaton();
Gnfa g = Converter.INSTANCE.getGnfaFromAutomaton(a);
StateEliminator.INSTANCE.handleTrivialCases(g);
TopologicalOrderIterator<State, Transition> topOrder =
new TopologicalOrderIterator(g);
while (topOrder.hasNext()) {
State next = topOrder.next();
LOGGER.debug(next.getDotLabel());
}
Classifier.INSTANCE.classify(g);
LOGGER.debug(g.toDot());
}
示例15: cacheRegex
import org.jgrapht.traverse.TopologicalOrderIterator; //导入依赖的package包/类
private static void cacheRegex(String regex) {
String r = expandRegex(regex);
Automaton automaton = new RegExp(r, RegExp.NONE).toAutomaton();
automaton.expandSingleton();
// We convert this to a graph without self-loops in order to determine the topological order
DirectedGraph<State, DefaultEdge> regexGraph = new DefaultDirectedGraph<State, DefaultEdge>(
DefaultEdge.class);
Set<State> visitedStates = new HashSet<State>();
Queue<State> states = new LinkedList<State>();
State initialState = automaton.getInitialState();
states.add(initialState);
while (!states.isEmpty()) {
State currentState = states.poll();
if (visitedStates.contains(currentState))
continue;
if (!regexGraph.containsVertex(currentState))
regexGraph.addVertex(currentState);
for (Transition t : currentState.getTransitions()) {
// Need to get rid of back edges, otherwise there is no topological order!
if (!t.getDest().equals(currentState)) {
regexGraph.addVertex(t.getDest());
regexGraph.addEdge(currentState, t.getDest());
states.add(t.getDest());
CycleDetector<State, DefaultEdge> det = new CycleDetector<State, DefaultEdge>(
regexGraph);
if (det.detectCycles()) {
regexGraph.removeEdge(currentState, t.getDest());
}
}
}
visitedStates.add(currentState);
}
TopologicalOrderIterator<State, DefaultEdge> iterator = new TopologicalOrderIterator<State, DefaultEdge>(
regexGraph);
List<State> topologicalOrder = new ArrayList<State>();
while (iterator.hasNext()) {
topologicalOrder.add(iterator.next());
}
regexStateCache.put(regex, topologicalOrder);
regexAutomatonCache.put(regex, automaton);
}