org.jgrapht.graph.DefaultDirectedGraph Java Examples

The following examples show how to use org.jgrapht.graph.DefaultDirectedGraph. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BuildTGDStratification.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
private DirectedGraph<TGDStratum, DefaultEdge> buildStrataGraph(DirectedGraph<Dependency, DefaultEdge> dependencyGraph, List<TGDStratum> tgdStrata) {
    DirectedGraph<TGDStratum, DefaultEdge> strataGraph = new DefaultDirectedGraph<TGDStratum, DefaultEdge>(DefaultEdge.class);
    for (TGDStratum stratum : tgdStrata) {
        strataGraph.addVertex(stratum);
    }
    for (TGDStratum stratumA : tgdStrata) {
        for (TGDStratum stratumB : tgdStrata) {
            if(stratumA.equals(stratumB)){
                continue;
            }
            if (existsPath(dependencyGraph, stratumA, stratumB)) {
                strataGraph.addEdge(stratumA, stratumB);
            }
        }
    }
    return strataGraph;
}
 
Example #2
Source File: AbstractRMLProcessor.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
private static boolean addCondition(TriplesMap from, TriplesMap target,
		DefaultDirectedGraph<TriplesMap, DefaultEdge> xx) {

	if (xx.containsEdge(from, target)) {
		return false;
	}
	xx.addVertex(from);
	xx.addVertex(target);

	Set<DefaultEdge> incoming = xx.incomingEdgesOf(target);
	DefaultEdge incedge = null;
	for (DefaultEdge e : incoming) {
		incedge = e;
		break;
	}
	if (incedge == null) {
		xx.addEdge(from, target);
	} else {
		manage(incedge, from, xx);
	}
	return true;
}
 
Example #3
Source File: AbstractRMLProcessor.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
private static void manage(DefaultEdge incomingedge, TriplesMap from,
		DefaultDirectedGraph<TriplesMap, DefaultEdge> xx) {
	TriplesMap incomingFromVertex = xx.getEdgeSource(incomingedge);
	TriplesMap incomingTargetVertex = xx.getEdgeTarget(incomingedge);
	if (sorted(incomingFromVertex, from)) {
		// put it here
		xx.removeEdge(incomingedge);
		xx.addEdge(incomingFromVertex, from);
		xx.addEdge(from, incomingTargetVertex);
	} else {
		Set<DefaultEdge> incoming = xx.incomingEdgesOf(incomingFromVertex);
		DefaultEdge incedge = null;
		for (DefaultEdge e : incoming) {
			incedge = e;
			break;
		}
		if (incedge == null) {
			xx.addEdge(from, incomingFromVertex);
		} else {
			manage(incedge, from, xx);
		}
	}
	// Set<DefaultEdge> incoming = xx.incomingEdgesOf(xx
	// .getEdgeSource(incomingedge));
	// it should be only one incoming
}
 
Example #4
Source File: GenerateStratification.java    From BART with MIT License 6 votes vote down vote up
private DirectedGraph<Dependency, DefaultEdge> initDependencyGraph(List<Dependency> dependencies, Map<Dependency, Set<AttributeRef>> affectedAttributes, Map<Dependency, Set<AttributeRef>> queriedAttributes) {
    DirectedGraph<Dependency, DefaultEdge> dependencyGraph = new DefaultDirectedGraph<Dependency, DefaultEdge>(DefaultEdge.class);
    for (Dependency dependency : dependencies) {
        dependencyGraph.addVertex(dependency);
    }
    for (int i = 0; i < dependencies.size(); i++) {
        Dependency d1 = dependencies.get(i);
        for (int j = 0; j < dependencies.size(); j++) {
            if (i == j) {
                continue;
            }
            Dependency d2 = dependencies.get(j);
            if (haveOverlap(d1, d2, affectedAttributes, queriedAttributes)) {
                if (logger.isDebugEnabled()) logger.debug("Edge btw " + d1.getId() + " and " + d2.getId());
                dependencyGraph.addEdge(d1, d2);
            }
        }
    }
    return dependencyGraph;
}
 
Example #5
Source File: RefreshOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).put("value", "A").build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).put("value", "C").build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation, times(3)).executeQuery(eq(connection), queryCaptor.capture());
    final List<String> queries = queryCaptor.getAllValues();
    assertThat(queries.get(0), containsString("MERGE (n1:A {id:1}) SET n1.value=\"A\""));
    assertThat(queries.get(1), containsString("MERGE (n2:A {id:2})"));
    assertThat(queries.get(2), containsString("MATCH (n1:A {id:1}),(n2:A {id:2}) MERGE (n1)-[e1:E]->(n2) SET e1.id=3,e1.value=\"C\""));
}
 
Example #6
Source File: UpdateOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).put("value", "A").build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).put("value", "C").build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation, times(2)).executeQuery(eq(connection), queryCaptor.capture());
    final List<String> queries = queryCaptor.getAllValues();
    assertThat(queries.get(0), containsString("MATCH (n1:A {id:1}) SET n1.value=\"A\""));
    assertThat(queries.get(1), containsString("MATCH (n1:A {id:1}),(n2:A {id:2}) MERGE (n1)-[e1:E]->(n2) SET e1.id=3,e1.value=\"C\""));
}
 
Example #7
Source File: DeleteAllOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"), Collections.emptyMap());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation, times(2)).executeQuery(eq(connection), queryCaptor.capture());
    final String query = queryCaptor.getValue();
    assertThat(query, containsString("MATCH (n:A) DETACH DELETE n"));
}
 
Example #8
Source File: InsertOperationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() throws Exception {
    // GIVEN
    final Node n1 = graphElementFactory.createNode("n1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node n2 = graphElementFactory.createNode("n2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(n1, n2, "e1", Arrays.asList("E"),
            ImmutableMap.<String, Object>builder().put("id", 3l).build());

    final Graph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    graph.addVertex(n1);
    graph.addVertex(n2);
    graph.addEdge(e1.getSourceNode(), e1.getTargetNode(), e1);

    // WHEN
    operation.execute(connection, graph);

    // THEN
    final ArgumentCaptor<String> queryCaptor = ArgumentCaptor.forClass(String.class);
    verify(operation).executeQuery(eq(connection), queryCaptor.capture());
    final String query = queryCaptor.getValue();
    assertThat(query, containsString("CREATE (n1:A {id:1}),(n2:A {id:2}),(n1)-[e1:E {id:3}]->(n2)"));
}
 
Example #9
Source File: BuildEGDStratification.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
private DirectedGraph<EGDStratum, DefaultEdge> buildEGDStrataGraph(DirectedGraph<ExtendedEGD, DefaultEdge> dependencyGraph, List<EGDStratum> egdStrata) {
    DirectedGraph<EGDStratum, DefaultEdge> strataGraph = new DefaultDirectedGraph<EGDStratum, DefaultEdge>(DefaultEdge.class);
    for (EGDStratum stratum : egdStrata) {
        strataGraph.addVertex(stratum);
    }
    for (EGDStratum stratumA : egdStrata) {
        for (EGDStratum stratumB : egdStrata) {
            if(stratumA.equals(stratumB)){
                continue;
            }
            if (existsPath(dependencyGraph, stratumA, stratumB)) {
                strataGraph.addEdge(stratumA, stratumB);
            }
        }
    }
    return strataGraph;
}
 
Example #10
Source File: RunnableTaskDagBuilder.java    From workflow with Apache License 2.0 6 votes vote down vote up
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));
    }
}
 
Example #11
Source File: DirectedGraphUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void createDirectedGraph() {
    directedGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
    IntStream.range(1, 10).forEach(i -> {
        directedGraph.addVertex("v" + i);
    });
    directedGraph.addEdge("v1", "v2");
    directedGraph.addEdge("v2", "v4");
    directedGraph.addEdge("v4", "v3");
    directedGraph.addEdge("v3", "v1");
    directedGraph.addEdge("v5", "v4");
    directedGraph.addEdge("v5", "v6");
    directedGraph.addEdge("v6", "v7");
    directedGraph.addEdge("v7", "v5");
    directedGraph.addEdge("v8", "v5");
    directedGraph.addEdge("v9", "v8");
}
 
Example #12
Source File: Import.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
private IExpr graphImport(Reader reader, Extension format, EvalEngine engine) throws ImportException {
	Graph<IExpr, ExprEdge> result;
	switch (format) {
	case DOT:
		DOTImporter<IExpr, ExprEdge> dotImporter = new DOTImporter<IExpr, ExprEdge>(
				(label, attributes) -> engine.parse(label), (from, to, label, attributes) -> new ExprEdge());
		result = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		dotImporter.importGraph(result, reader);
		return GraphExpr.newInstance(result);
	case GRAPHML:
		result = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		Map<String, Map<String, Attribute>> vertexAttributes = new HashMap<>();
		Map<ExprEdge, Map<String, Attribute>> edgeAttributes = new HashMap<ExprEdge, Map<String, Attribute>>();
		GraphMLImporter<IExpr, ExprEdge> graphmlImporter = createGraphImporter(result, vertexAttributes,
				edgeAttributes, engine);
		graphmlImporter.importGraph(result, reader);
		return GraphExpr.newInstance(result);
	default:
	}
	return F.NIL;
}
 
Example #13
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
	try {
		if (ast.isAST1()) {
			GraphExpr<ExprEdge> gex = createGraph(ast.arg1());
			if (gex == null) {
				return F.NIL;
			}
			Graph<IExpr, ExprEdge> g = gex.toData();
			SpanningTreeAlgorithm<ExprEdge> k = new BoruvkaMinimumSpanningTree<IExpr, ExprEdge>(g);
			Set<ExprEdge> edgeSet = k.getSpanningTree().getEdges();
			Graph<IExpr, ExprEdge> gResult = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
			Graphs.addAllEdges(gResult, g, edgeSet);
			return GraphExpr.newInstance(gResult);
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #14
Source File: ModelInfoGraphBuilder.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ModelInfoGraphBuilder(JsonixContext context,
		MModelInfo<T, C> modelInfo) {
	Validate.notNull(modelInfo);
	this.logger = Validate.notNull(context).getLoggerFactory()
			.getLogger(ModelInfoGraphAnalyzer.class.getName());
	this.modelInfo = modelInfo;
	this.graph = new DefaultDirectedGraph<InfoVertex<T, C>, DependencyEdge>(
			this.edgeFactory);
}
 
Example #15
Source File: AnalyzeDependencies.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private DirectedGraph<AttributeRef, ExtendedEdge> removeSpecialEdges(DirectedGraph<AttributeRef, ExtendedEdge> faginDependencyGraph) {
    DirectedGraph<AttributeRef, ExtendedEdge> dependencyGraph = new DefaultDirectedGraph<AttributeRef, ExtendedEdge>(ExtendedEdge.class);
    if (faginDependencyGraph == null) {
        return dependencyGraph;
    }
    Graphs.addGraph(dependencyGraph, faginDependencyGraph);
    for (ExtendedEdge edge : faginDependencyGraph.edgeSet()) {
        if (edge.isSpecial() && !edge.isNormal()) {
            dependencyGraph.removeEdge(edge);
        }
    }
    return dependencyGraph;
}
 
Example #16
Source File: ClassDependenciesGraph.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
ClassDependenciesGraph(TestVerifier testVerifier, Configuration configuration, File projectDir) {
    this.builder = new JavaClassBuilder();
    this.graph = new DefaultDirectedGraph<>(DefaultEdge.class);
    final AffectedConfiguration affectedConfiguration =
        (AffectedConfiguration) configuration.getStrategyConfiguration(AFFECTED);
    this.filter = new Filter(affectedConfiguration.getInclusions(), affectedConfiguration.getExclusions());
    this.testVerifier = testVerifier;
    this.enableTransitivity = affectedConfiguration.isTransitivity();
    this.projectDir = projectDir.toPath();
    this.watchFilesResolver = new WatchFilesResolver(this.projectDir);
    this.componentUnderTestResolver = new ComponentUnderTestResolver();
    this.elementAdapter = new ElementAdapter(this.testVerifier, this.builder);
}
 
Example #17
Source File: BuildTGDStratification.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private DirectedGraph<Dependency, DefaultEdge> buildChaseGraph(Map<Dependency, Set<Dependency>> affectedDependencies) {
    DirectedGraph<Dependency, DefaultEdge> chaseGraph = new DefaultDirectedGraph<Dependency, DefaultEdge>(DefaultEdge.class);
    for (Dependency tgd : affectedDependencies.keySet()) {
        chaseGraph.addVertex(tgd);
    }
    for (Dependency dependency : affectedDependencies.keySet()) {
        for (Dependency connectedDependency : affectedDependencies.get(dependency)) {
            chaseGraph.addEdge(dependency, connectedDependency);
        }
    }
    return chaseGraph;
}
 
Example #18
Source File: RunnableTaskDagBuilder.java    From workflow with Apache License 2.0 5 votes vote down vote up
private void worker(DefaultDirectedGraph<TaskId, DefaultEdge> graph, Task task, TaskId parentId, ImmutableMap.Builder<TaskId, Task> tasksBuilder, Set<TaskId> usedTasksSet)
{
    if ( usedTasksSet.add(task.getTaskId()) )
    {
        tasksBuilder.put(task.getTaskId(), task);
    }

    graph.addVertex(task.getTaskId());
    if ( parentId != null )
    {
        graph.addEdge(parentId, task.getTaskId());
    }
    task.getChildrenTasks().forEach(child -> worker(graph, child, task.getTaskId(), tasksBuilder, usedTasksSet));
}
 
Example #19
Source File: GenerateDOTMojo.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
DirectedGraph<AddonVertex, AddonDependencyEdge> toGraph(AddonDependencyResolver addonResolver, AddonInfo info)
{
   DirectedGraph<AddonVertex, AddonDependencyEdge> graph = new DefaultDirectedGraph<AddonVertex, AddonDependencyEdge>(
            AddonDependencyEdge.class);
   populateGraph(addonResolver, info, graph);
   return graph;
}
 
Example #20
Source File: GraphImageGenerationUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Before
public void createGraph() throws IOException {
    File imgFile = new File("src/test/resources/graph.png");
    imgFile.createNewFile();
    g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
    String x1 = "x1";
    String x2 = "x2";
    String x3 = "x3";
    g.addVertex(x1);
    g.addVertex(x2);
    g.addVertex(x3);
    g.addEdge(x1, x2);
    g.addEdge(x2, x3);
    g.addEdge(x3, x1);
}
 
Example #21
Source File: BuildFaginDependencyGraph.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
public DirectedGraph<AttributeRef, ExtendedEdge> buildGraph(List<Dependency> extTGDs) {
    if (extTGDs.isEmpty()) {
        return null;
    }
    if (logger.isDebugEnabled()) logger.debug("**** Checking weakly acyclicity");
    DirectedGraph<AttributeRef, ExtendedEdge> dependencyGraph = new DefaultDirectedGraph<AttributeRef, ExtendedEdge>(ExtendedEdge.class);
    Set<AttributeRef> positionsAdded = new HashSet<AttributeRef>();
    for (Dependency extTGD : extTGDs) {
        addNodes(dependencyGraph, extTGD.getPremise(), positionsAdded);
        addNodes(dependencyGraph, extTGD.getConclusion(), positionsAdded);
        addEdges(dependencyGraph, extTGD);
    }
    if (logger.isDebugEnabled()) logger.debug("Dependency graph: " + dependencyGraph);
    return dependencyGraph;
}
 
Example #22
Source File: CheckConflicts.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private DirectedGraph<AttributeRef, DefaultEdge> buildTGDPropagationGraph(Scenario scenario) {
    List<Dependency> tgds = new ArrayList<Dependency>();
    tgds.addAll(scenario.getSTTgds());
    tgds.addAll(scenario.getExtTGDs());
    DirectedGraph<AttributeRef, DefaultEdge> dependencyGraph = new DefaultDirectedGraph<AttributeRef, DefaultEdge>(DefaultEdge.class);
    addVertices(scenario.getSource(), true, dependencyGraph);
    addVertices(scenario.getTarget(), false, dependencyGraph);
    for (Dependency tgd : tgds) {
        addEdges(dependencyGraph, tgd);
    }
    return dependencyGraph;
}
 
Example #23
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create an internal DataExpr Graph.
 * 
 * @param arg1
 * @return
 */
private static GraphExpr<ExprEdge> createGraph(final IExpr arg1) {
	if (arg1.head().equals(F.Graph) && arg1 instanceof GraphExpr) {
		return (GraphExpr<ExprEdge>) arg1;
	}
	Graph<IExpr, ExprEdge> g;
	GraphType t = arg1.isListOfEdges();
	if (t != null) {
		if (t.isDirected()) {
			g = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		} else {
			g = new DefaultUndirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
		}

		IAST list = (IAST) arg1;
		for (int i = 1; i < list.size(); i++) {
			IAST edge = list.getAST(i);
			g.addVertex(edge.arg1());
			g.addVertex(edge.arg2());
			g.addEdge(edge.arg1(), edge.arg2());
		}

		return GraphExpr.newInstance(g);
	}

	return null;
}
 
Example #24
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static GraphExpr createGraph(final IAST vertices, final IAST edges) {

		Graph<IExpr, ExprEdge> g;
		GraphType t = edges.isListOfEdges();
		if (t != null) {
			if (t.isDirected()) {
				g = new DefaultDirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
			} else {
				g = new DefaultUndirectedGraph<IExpr, ExprEdge>(ExprEdge.class);
			}
			if (vertices.isList()) {
				// Graph<IExpr, IExprEdge> g = new DefaultDirectedGraph<IExpr, IExprEdge>(IExprEdge.class);
				for (int i = 1; i < vertices.size(); i++) {
					g.addVertex(vertices.get(i));
				}
			}

			for (int i = 1; i < edges.size(); i++) {
				IAST edge = edges.getAST(i);
				g.addVertex(edge.arg1());
				g.addVertex(edge.arg2());
				g.addEdge(edge.arg1(), edge.arg2());
			}

			return GraphExpr.newInstance(g);
		}

		return null;
	}
 
Example #25
Source File: CleanupStrategyProviderIT.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private static List<Graph<Node, Edge>> loadDataSet(final String path) {
    try {
        final URL resource = Thread.currentThread().getContextClassLoader().getResource(path);
        final File file = new File(resource.toURI());

        final DefaultDirectedGraph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
        final GraphMLReader<Node, Edge> importer = new GraphMLReader<>(factory, factory);
        importer.importGraph(graph, file);

        return Arrays.asList(graph);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicOrderingWithComparator() {
    SortableDependency sp1 = newVertex("sp1");
    SortableDependency sp2 = newVertex("sp2");
    SortableDependency sp3 = newVertex("sp3");
    SortableDependency sp4 = newVertex("sp4");
    SortableDependency sp5 = newVertex("sp5");

    Graph<SortableDependency, DefaultEdge> graph = new DefaultDirectedGraph<SortableDependency, DefaultEdge>(DefaultEdge.class);

    for (SortableDependency vertex : shuffledList(sp1, sp2, sp3, sp4, sp5)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);

    ListIterable<SortableDependency> sorted = sorter.sortChanges(graph, Comparators.fromFunctions(new Function<SortableDependency, String>() {
        @Override
        public String valueOf(SortableDependency sortableDependency) {
            return sortableDependency.getChangeKey().getChangeName();
        }
    }));

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(5, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp1)));
    assertThat(sorted.indexOf(sp5), greaterThan(sorted.indexOf(sp3)));
    assertThat(sorted.indexOf(sp4), greaterThan(sorted.indexOf(sp5)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3, sp5, sp4), sorted);
}
 
Example #27
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void expectExceptionIfNonComparableElementsAreProvidedForSorting() {
    SortableDependency sp1 = newVertex("sp1");

    Graph<SortableDependency, DefaultEdge> graph = new DefaultDirectedGraph<SortableDependency, DefaultEdge>(DefaultEdge.class);

    for (SortableDependency vertex : shuffledList(sp1)) {
        graph.addVertex(vertex);
    }

    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("Unsortable graph elements");

    sorter.sortChanges(graph);
}
 
Example #28
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testOrderingWithSubgraph() {
    String sp1 = "sp1";
    String sp2 = "sp2";
    String sp3 = "sp3";
    String sp4 = "sp4";
    String sp5 = "sp5";

    Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);

    for (String vertex : shuffledList(sp1, sp2, sp3, sp4, sp5)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);
    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);

    ImmutableList<String> sorted = sorter.sortChanges(graph, Lists.mutable.with(sp1, sp2, sp3));

    // First, compare the root topological order (i.e. ensure that the dependencies are respected)
    assertEquals(3, sorted.size());
    assertThat(sorted.indexOf(sp1), greaterThan(sorted.indexOf(sp2)));

    // Now check that we can achieve a consistent order too (for easier debuggability for clients)
    assertEquals(Lists.immutable.with(sp2, sp1, sp3), sorted);
}
 
Example #29
Source File: GraphSorterTest.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCycleDetection() {
    SortableDependency sp1 = newVertex("sp1");
    SortableDependency sp2 = newVertex("sp2");
    SortableDependency sp3 = newVertex("sp3");
    SortableDependency sp4 = newVertex("sp4");
    SortableDependency sp5 = newVertex("sp5");
    SortableDependency sp6 = newVertex("sp6");
    SortableDependency sp7 = newVertex("sp7");
    SortableDependency sp8 = newVertex("sp8");

    Graph<SortableDependency, DefaultEdge> graph = new DefaultDirectedGraph<SortableDependency, DefaultEdge>(DefaultEdge.class);
    for (SortableDependency vertex : shuffledList(sp1, sp2, sp3, sp4, sp5, sp6, sp7, sp8)) {
        graph.addVertex(vertex);
    }

    graph.addEdge(sp2, sp1);
    graph.addEdge(sp5, sp4);
    graph.addEdge(sp1, sp5);
    graph.addEdge(sp3, sp5);
    graph.addEdge(sp4, sp5);
    graph.addEdge(sp6, sp5);
    graph.addEdge(sp7, sp6);
    graph.addEdge(sp8, sp7);
    graph.addEdge(sp6, sp8);

    try {
        sorter.sortChanges(graph);
        fail("Expecting exception here: " + GraphCycleException.class);
    } catch (GraphCycleException e) {
        verifyCycleExists(e, Sets.immutable.with("sp4", "sp5"));
        verifyCycleExists(e, Sets.immutable.with("sp6", "sp7", "sp8"));
        Verify.assertSize(2, e.getCycleComponents());
    }
}
 
Example #30
Source File: DatabaseReader.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
public Graph<Node, Edge> readGraph(final Connection connection) throws SQLException {
    final List<Node> nodes = new ArrayList<>();
    final List<Edge> edges = new ArrayList<>();

    readGraphElements(connection, edges, nodes);

    final DefaultDirectedGraph<Node, Edge> graph = new DefaultDirectedGraph<>(new ClassBasedEdgeFactory<>(Edge.class));
    nodes.forEach(graph::addVertex);
    edges.forEach(e -> graph.addEdge(e.getSourceNode(), e.getTargetNode(), e));

    return graph;
}