org.jgrapht.Graph Java Examples

The following examples show how to use org.jgrapht.Graph. 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: CleanupStrategyProvider.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Override
public CleanupStrategyExecutor<Connection, Graph<Node, Edge>> usedTablesOnlyStrategy() {
    return (final Connection connection, final List<Graph<Node, Edge>> initialGraphs, final String... nodeTypesToRetain) -> {
        if (initialGraphs.isEmpty()) {
            return;
        }

        try {
            for (final Graph<Node, Edge> graph : initialGraphs) {
                Neo4JOperations.DELETE_ALL.execute(connection, computeGraphToBeDeleted(graph, nodeTypesToRetain));
            }

            connection.commit();
        } catch (final SQLException e) {
            throw new DbFeatureException(UNABLE_TO_CLEAN_DATABASE, e);
        }
    };
}
 
Example #2
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();
			GraphPath<IExpr, ExprEdge> path = hamiltonianCycle(g);
			if (path != null) {
				// Graph is Hamiltonian
				return F.True;
			}
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.False;
}
 
Example #3
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
private static void init() {
	F.Graph.setEvaluator(new GraphCTor());
	F.GraphCenter.setEvaluator(new GraphCenter());
	F.GraphDiameter.setEvaluator(new GraphDiameter());
	F.GraphPeriphery.setEvaluator(new GraphPeriphery());
	F.GraphRadius.setEvaluator(new GraphRadius());
	F.AdjacencyMatrix.setEvaluator(new AdjacencyMatrix());
	F.EdgeList.setEvaluator(new EdgeList());
	F.EdgeQ.setEvaluator(new EdgeQ());
	F.EulerianGraphQ.setEvaluator(new EulerianGraphQ());
	F.FindEulerianCycle.setEvaluator(new FindEulerianCycle());
	F.FindHamiltonianCycle.setEvaluator(new FindHamiltonianCycle());
	F.FindVertexCover.setEvaluator(new FindVertexCover());
	F.FindShortestPath.setEvaluator(new FindShortestPath());
	F.FindShortestTour.setEvaluator(new FindShortestTour());
	F.FindSpanningTree.setEvaluator(new FindSpanningTree());
	F.GraphQ.setEvaluator(new GraphQ());
	F.HamiltonianGraphQ.setEvaluator(new HamiltonianGraphQ());
	F.VertexEccentricity.setEvaluator(new VertexEccentricity());
	F.VertexList.setEvaluator(new VertexList());
	F.VertexQ.setEvaluator(new VertexQ());
}
 
Example #4
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private FormulaWithAdornments findFormulaWithAdornments(UndirectedGraph<FormulaGraphVertex, DefaultEdge> formulaGraph,
        List<VariablePair> variablePairs, List<FormulaVariable> anonymousVariables, IFormula formula) {
    Set<FormulaGraphVertex> vertices = new HashSet<FormulaGraphVertex>(formulaGraph.vertexSet());
    for (VariablePair variablePair : variablePairs) {
        vertices.remove(variablePair.getVertex());
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> subgraph = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, vertices, formulaGraph.edgeSet());
    ConnectivityInspector<FormulaGraphVertex, DefaultEdge> inspector = new ConnectivityInspector<FormulaGraphVertex, DefaultEdge>(subgraph);
    List<Set<FormulaGraphVertex>> connectedVertices = inspector.connectedSets();
    if (connectedVertices.size() != 2) {
        return null;
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(0), formulaGraph.edgeSet());
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(1), formulaGraph.edgeSet());
    VertexEquivalenceComparator vertexComparator = new VertexEquivalenceComparator(variablePairs, anonymousVariables);
    UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>> edgeComparator = new UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>>();
    GraphIsomorphismInspector<Graph<FormulaGraphVertex, DefaultEdge>> isomorphismInspector = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector(connectedSubgraphOne, connectedSubgraphTwo, vertexComparator, edgeComparator);
    boolean areIsomorphic = isomorphismInspector.isIsomorphic();
    if (logger.isDebugEnabled()) logger.debug("Graph One: \n" + connectedSubgraphOne + "\nGraph Two: \n" + connectedSubgraphTwo + "\nAre isomorphic: " + areIsomorphic);
    if (!areIsomorphic) {
        return null;
    }
    return formulaWithAdornmentsGenerator.generate(formula, connectedSubgraphOne, connectedSubgraphTwo, variablePairs);
}
 
Example #5
Source File: GamaSpatialPath.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public IList<IShape> getPathVertexList() {
	final Graph<IShape, IShape> g = getGraph();
	try (final Collector.AsList<IShape> list = Collector.getList()) {
		IShape v = getStartVertex();
		list.add(v);
		IShape vPrev = null;
		for (final IShape e : getEdgeList()) {
			vPrev = v;
			v = getOppositeVertex(g, e, v);
			if (!v.equals(vPrev)) {
				list.add(v);
			}
		}
		return list.items();
	}
}
 
Example #6
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();
			return graphToAdjacencyMatrix(g);
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #7
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 #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: 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 {
		GraphExpr<ExprEdge> gex = createGraph(ast.arg1());
		if (gex == null) {
			return F.NIL;
		}
		Graph<IExpr, ExprEdge> g = gex.toData();

		GraphMeasurer<IExpr, ExprEdge> graphMeasurer = new GraphMeasurer<>(g);
		INum radius = F.num(graphMeasurer.getRadius());
		if (gex.isWeightedGraph()) {
			return radius;
		}
		int intRadius = radius.toIntDefault();
		if (intRadius != Integer.MIN_VALUE) {
			return F.ZZ(intRadius);
		}
		return radius;
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #10
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();
			return vertexToIExpr(g);
			// Set<IExpr> vertexSet = g.vertexSet();
			// int size = vertexSet.size();
			// IASTAppendable result = F.ListAlloc(size);
			// for (IExpr expr : vertexSet) {
			// result.append(expr);
			// }
			// return result;
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #11
Source File: GraphComparator.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
private void checkPresenceOfExpectedNodes(final Graph<Node, Edge> givenGraph, final Graph<Node, Edge> expectedGraph,
        final AssertionErrorCollector errorCollector) {
    for (final Node expectedNode : expectedGraph.vertexSet()) {

        final List<String> attributesToExclude = expectedNode.getLabels().stream().map(toExclude::getColumns).flatMap(List::stream)
                .distinct().collect(toList());

        final List<Node> availableNodesOfExpectedType = givenGraph.vertexSet().stream()
                .filter(n -> n.getType().equals(expectedNode.getType())).collect(toList());

        final List<Node> foundNodes = availableNodesOfExpectedType.stream().filter(n -> n.isSame(expectedNode, attributesToExclude))
                .collect(toList());

        if (foundNodes.isEmpty()) {
            errorCollector.collect(expectedNode.asString() + " was expected, but is not present");
        } else if (foundNodes.size() > 1) {
            errorCollector.collect("Ambiguouty detected for node " + expectedNode.asString() + " for given attribute filter");
        }
    }
}
 
Example #12
Source File: QueryGraphBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds a single edge to the graph
 * @param graph
 * @param edefEdge
 */
private void addEdgeToGraph(Graph<IModelEntity, Relationship> graph, DefaultEdge edefEdge){
	if(edefEdge!=null){
		Relationship edge = (Relationship)edefEdge;
		IModelEntity src= edge.getSourceEntity();
		IModelEntity target= edge.getTargetEntity();

		if(!vertexes.contains(src)){
			logger.debug("Add the vertex "+src.getName());
			vertexes.add(src);
			graph.addVertex(src);
		}
		if(!vertexes.contains(target)){
			logger.debug("Add the vertex "+src.getName());
			vertexes.add(target);
			graph.addVertex(target);
		}

		logger.debug("Add the edge "+src.getName()+"--"+target.getName());
		graph.addEdge(src, target, edge);
	}
	logger.debug("OUT");
}
 
Example #13
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
private static void vertexToVisjs(Map<IExpr, Integer> map, StringBuilder buf, Graph<IExpr, ?> g) {
	Set<IExpr> vertexSet = g.vertexSet();
	IASTAppendable vertexes = F.ListAlloc(vertexSet.size());
	buf.append("var nodes = new vis.DataSet([\n");
	boolean first = true;
	int counter = 1;
	for (IExpr expr : vertexSet) {
		// {id: 1, label: 'Node 1'},
		if (first) {
			buf.append("  {id: ");
		} else {
			buf.append(", {id: ");
		}
		buf.append(counter);
		map.put(expr, counter++);
		buf.append(", label: '");
		buf.append(expr.toString());
		buf.append("'}\n");
		first = false;
	}
	buf.append("]);\n");
}
 
Example #14
Source File: QueryGraphBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public Graph<IModelEntity, Relationship> buildGraphFromPaths(Collection<GraphPath<IModelEntity, Relationship>> paths){
	logger.debug("IN");
	Assert.assertNotNull(paths, "The list of paths is null. Impossbile to create a graph");
	logger.debug("The number of paths is "+paths.size());

	UndirectedGraph<IModelEntity, Relationship> graph = new Multigraph<IModelEntity, Relationship>(Relationship.class);
	
	if(paths!=null){
		Iterator<GraphPath<IModelEntity, Relationship>> pathIter = paths.iterator();
		while(pathIter.hasNext()){
			GraphPath<IModelEntity, Relationship> path = pathIter.next();
			addPathToGraph(graph, path);
		}
	}

	logger.debug("OUT");
	return graph;
}
 
Example #15
Source File: AbstractPointRouterFactory.java    From openAGV with Apache License 2.0 6 votes vote down vote up
@Override
public PointRouter createPointRouter(Vehicle vehicle) {
  requireNonNull(vehicle, "vehicle");

  long timeStampBefore = System.currentTimeMillis();

  Set<Point> points = objectService.fetchObjects(Point.class);
  Graph<String, ModelEdge> graph = mapper.translateModel(points,
                                                         objectService.fetchObjects(Path.class),
                                                         vehicle);

  PointRouter router = new ShortestPathPointRouter(createShortestPathAlgorithm(graph), points);
  // Make a single request for a route from one point to a different one to make sure the
  // point router is primed. (Some implementations are initialized lazily.)
  if (points.size() >= 2) {
    Iterator<Point> pointIter = points.iterator();
    router.getRouteSteps(pointIter.next(), pointIter.next());
  }

  LOG.debug("Created point router for {} in {} milliseconds.",
            vehicle.getName(),
            System.currentTimeMillis() - timeStampBefore);

  return router;
}
 
Example #16
Source File: DeleteAllOperation.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final Connection connection, final Graph<Node, Edge> graph) throws SQLException {
    for (final Node node : graph.vertexSet()) {

        final StartNext match = match(node.toPath().withId("n").build());

        executeQuery(connection, match.toString() + " DETACH DELETE n");
    }
}
 
Example #17
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 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();
			// ChordalityInspector<IExpr, IExprEdge> inspector = new ChordalityInspector<IExpr, IExprEdge>(g);
			VertexCoverAlgorithm<IExpr> greedy = new GreedyVCImpl<>(g);
			VertexCoverAlgorithm.VertexCover<IExpr> cover = greedy.getVertexCover();
			if (cover == null) {
				return F.List();
			}
			IASTAppendable result = F.ListAlloc(10);
			cover.forEach(x -> result.append(x));
			return result;
		}
	} catch (IllegalArgumentException iae) {
		return engine.printMessage("Graph must be undirected");
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #18
Source File: GraphComparator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
public void compare(final Connection connection, final Graph<Node, Edge> expectedGraph, final AssertionErrorCollector errorCollector) {
    Graph<Node, Edge> givenGraph;
    try {
        givenGraph = dbReader.readGraph(connection);
    } catch (final SQLException e) {
        throw new JpaUnitException(FAILED_TO_VERIFY_DATA_BASE_STATE, e);
    }

    if (expectedGraph.vertexSet().isEmpty()) {
        shouldBeEmpty(givenGraph, errorCollector);
    } else {
        compareContent(givenGraph, expectedGraph, errorCollector);
    }
}
 
Example #19
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Create an eulerian cycle.
 * 
 * @param g
 * @return <code>null</code> if no eulerian cycle can be created
 */
private static GraphPath<IExpr, ExprEdge> eulerianCycle(Graph<IExpr, ExprEdge> g) {
	EulerianCycleAlgorithm<IExpr, ExprEdge> eca = new HierholzerEulerianCycle<>();
	try {
		return eca.getEulerianCycle(g);
	} catch (IllegalArgumentException iae) {
		// Graph is not Eulerian
	}
	return null;
}
 
Example #20
Source File: GraphMLReader.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public void importGraph(final Graph<V, E> graph, final Reader in) throws ImportException {
    try {
        final SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        final SAXParser saxParser = spf.newSAXParser();
        final XMLReader xmlReader = saxParser.getXMLReader();
        final GraphMLHandler<V, E> handler = new GraphMLHandler<>(graph, vertexProvider, edgeProvider);
        xmlReader.setContentHandler(handler);
        xmlReader.setErrorHandler(handler);
        xmlReader.parse(new InputSource(in));
    } catch (final Exception se) {
        throw new ImportException("Failed to parse GraphML", se);
    }
}
 
Example #21
Source File: GraphComparatorTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCompareGraphsForEmptyExpectedGraphAndNotEmptyGivenGraph() throws Exception {
    // GIVEN
    final Node a = graphElementFactory.createNode("a", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node b = graphElementFactory.createNode("b", Arrays.asList("B"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e = graphElementFactory.createEdge(a, b, "e", Arrays.asList("E"), Collections.emptyMap());

    final Graph<Node, Edge> expectedGraph = createGraph(Collections.emptyList(), Collections.emptyList());
    final Graph<Node, Edge> givenGraph = createGraph(Arrays.asList(a, b), Arrays.asList(e));

    final GraphComparator comparator = new GraphComparator(graphElementFactory, new String[] {}, false);
    when(dbReader.readGraph(connection)).thenReturn(givenGraph);

    // WHEN
    comparator.compare(connection, expectedGraph, errorCollector);

    // THEN
    final ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
    verify(errorCollector, times(2)).collect(stringCaptor.capture());

    final List<String> capturedMessages = stringCaptor.getAllValues();
    assertThat(capturedMessages, hasItems(containsString("No nodes with A labels were expected, but there are <1> nodes present"),
            containsString("No nodes with B labels were expected, but there are <1> nodes present")));
}
 
Example #22
Source File: GraphComparatorTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCompareFullyDistinctGraphsInNotStrictMode() throws Exception {
    // GIVEN
    final Node a1 = graphElementFactory.createNode("a1", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node a2 = graphElementFactory.createNode("a2", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e1 = graphElementFactory.createEdge(a1, a2, "e", Arrays.asList("E"), Collections.emptyMap());

    final Node b1 = graphElementFactory.createNode("b1", Arrays.asList("B"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node b2 = graphElementFactory.createNode("b2", Arrays.asList("B"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge f2 = graphElementFactory.createEdge(b1, b2, "f", Arrays.asList("F"), Collections.emptyMap());

    final Graph<Node, Edge> expectedGraph = createGraph(Arrays.asList(a1, a2), Arrays.asList(e1));
    final Graph<Node, Edge> givenGraph = createGraph(Arrays.asList(b1, b2), Arrays.asList(f2));

    final GraphComparator comparator = new GraphComparator(graphElementFactory, new String[] {}, false);
    when(dbReader.readGraph(connection)).thenReturn(givenGraph);

    // WHEN
    comparator.compare(connection, expectedGraph, errorCollector);

    // THEN
    final ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
    verify(errorCollector, times(4)).collect(stringCaptor.capture());

    final List<String> capturedMessages = stringCaptor.getAllValues();
    assertThat(capturedMessages,
            hasItems(containsString("Nodes with A labels were expected to be present, but not found"),
                    containsString(a1.asString() + " was expected, but is not present"),
                    containsString(a2.asString() + " was expected, but is not present"),
                    containsString(e1.asString() + " was expected, but is not present")));
}
 
Example #23
Source File: GraphComparator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void checkAbsenseOfNotExpectedReferences(final Graph<Node, Edge> givenGraph, final Graph<Node, Edge> expectedGraph,
        final AssertionErrorCollector errorCollector) {
    final List<List<String>> expectedEdgeLables = expectedGraph.edgeSet().stream().map(Edge::getLabels).distinct().collect(toList());

    for (final List<String> labels : expectedEdgeLables) {
        final List<Edge> expectedEdges = expectedGraph.edgeSet().stream().filter(node -> node.getLabels().containsAll(labels))
                .collect(toList());

        final List<String> edgeAttributesToExclude = labels.stream().map(toExclude::getColumns).flatMap(List::stream).distinct()
                .collect(toList());

        for (final Edge givenEdge : givenGraph.edgeSet()) {
            if (!givenEdge.getLabels().containsAll(labels)) {
                continue;
            }

            final boolean edgePresent = expectedEdges.stream().anyMatch(edge -> {
                final Set<Attribute> attributesToRetain = edge.getAttributes().stream()
                        .filter(a -> !edgeAttributesToExclude.contains(a.getName())).collect(toSet());

                final List<String> sourceNodeAttributesToExclude = edge.getSourceNode().getLabels().stream().map(toExclude::getColumns)
                        .flatMap(List::stream).distinct().collect(toList());

                final List<String> targetNodeAttributesToExclude = edge.getTargetNode().getLabels().stream().map(toExclude::getColumns)
                        .flatMap(List::stream).distinct().collect(toList());

                return givenEdge.getAttributes().containsAll(attributesToRetain)
                        && givenEdge.getSourceNode().isSame(edge.getSourceNode(), sourceNodeAttributesToExclude)
                        && givenEdge.getTargetNode().isSame(edge.getTargetNode(), targetNodeAttributesToExclude);
            });

            if (!edgePresent) {
                errorCollector.collect(givenEdge.asString() + " was not expected, but is present");
            }
        }
    }
}
 
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 IASTAppendable[] edgesToIExpr(Graph<IExpr, ?> g) {
	Set<Object> edgeSet = (Set<Object>) g.edgeSet();
	IASTAppendable edges = F.ListAlloc(edgeSet.size());
	IASTAppendable weights = null;
	GraphType type = g.getType();

	for (Object edge : edgeSet) {
		if (edge instanceof ExprWeightedEdge) {
			ExprWeightedEdge weightedEdge = (ExprWeightedEdge) edge;
			if (type.isDirected()) {
				edges.append(F.DirectedEdge(weightedEdge.lhs(), weightedEdge.rhs()));
			} else {
				edges.append(F.UndirectedEdge(weightedEdge.lhs(), weightedEdge.rhs()));
			}
			if (weights == null) {
				weights = F.ListAlloc(edgeSet.size());
			}
			weights.append(F.num(weightedEdge.weight()));
		} else if (edge instanceof ExprEdge) {
			ExprEdge exprEdge = (ExprEdge) edge;
			if (type.isDirected()) {
				edges.append(F.DirectedEdge(exprEdge.lhs(), exprEdge.rhs()));
			} else {
				edges.append(F.UndirectedEdge(exprEdge.lhs(), exprEdge.rhs()));
			}
		}
	}
	return new IASTAppendable[] { edges, weights };
}
 
Example #25
Source File: GraphUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static QueryGraph getCoverGraph(IDataSource dataSource, Query query) {
	QueryGraph queryGraph = null;
	IModelStructure modelStructure = dataSource.getModelStructure();
	RootEntitiesGraph rootEntitiesGraph = modelStructure.getRootEntitiesGraph(dataSource.getConfiguration().getModelName(), false);
	Graph<IModelEntity, Relationship> graph = rootEntitiesGraph.getRootEntitiesGraph();
	Set<IModelEntity> entities = query.getQueryEntities(dataSource);
	queryGraph = GraphManager.getDefaultCoverGraphInstance(null).getCoverGraph(graph, entities);
	return queryGraph;
}
 
Example #26
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static GraphPath<IExpr, ExprEdge> hamiltonianCycle(Graph<IExpr, ExprEdge> g) {
	HamiltonianCycleAlgorithm<IExpr, ExprEdge> eca = new HeldKarpTSP<>();
	try {
		return eca.getTour(g);
	} catch (IllegalArgumentException iae) {
		// Graph is not Hamiltonian
	}
	return null;
}
 
Example #27
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
@Override
public IExpr evaluate(final IAST ast, EvalEngine engine) {
	try {
		GraphExpr<ExprEdge> gex = createGraph(ast.arg1());
		if (gex == null) {
			return F.NIL;
		}
		Graph<IExpr, ExprEdge> g = gex.toData();
		// boolean pseudoDiameter = false;
		// if (ast.isAST2()) {
		// final OptionArgs options = new OptionArgs(ast.topHead(), ast, 2, engine);
		// IExpr option = options.getOption(F.Method);
		//
		// if (option.isPresent() && option.toString().equals("PseudoDiameter")) {
		// pseudoDiameter = true;
		// } else if (!option.isPresent()) {
		// return engine.printMessage("GraphPeriphery: Option PseudoDiameter expected!");
		// }
		// }

		GraphMeasurer<IExpr, ExprEdge> graphMeasurer = new GraphMeasurer<>(g);
		Set<IExpr> centerSet = graphMeasurer.getGraphPeriphery();
		IASTAppendable list = F.ListAlloc(centerSet.size());
		list.appendAll(centerSet);
		return list;
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #28
Source File: GraphComparatorTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testCompareGraphsForNotEmptyExpectedGraphButEmptyGivenGraph() throws Exception {
    // GIVEN
    final Node a = graphElementFactory.createNode("a", Arrays.asList("A"),
            ImmutableMap.<String, Object>builder().put("id", 1l).build());
    final Node b = graphElementFactory.createNode("b", Arrays.asList("B"),
            ImmutableMap.<String, Object>builder().put("id", 2l).build());
    final Edge e = graphElementFactory.createEdge(a, b, "e", Arrays.asList("E"), Collections.emptyMap());

    final Graph<Node, Edge> expectedGraph = createGraph(Arrays.asList(a, b), Arrays.asList(e));
    final Graph<Node, Edge> givenGraph = createGraph(Collections.emptyList(), Collections.emptyList());

    final GraphComparator comparator = new GraphComparator(graphElementFactory, new String[] {}, false);
    when(dbReader.readGraph(connection)).thenReturn(givenGraph);

    // WHEN
    comparator.compare(connection, expectedGraph, errorCollector);

    // THEN
    final ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
    verify(errorCollector, times(5)).collect(stringCaptor.capture());

    final List<String> capturedMessages = stringCaptor.getAllValues();
    assertThat(capturedMessages,
            hasItems(containsString("Nodes with A labels were expected to be present, but not found"),
                    containsString("Nodes with B labels were expected to be present, but not found"),
                    containsString(a.asString() + " was expected, but is not present"),
                    containsString(b.asString() + " was expected, but is not present"),
                    containsString(e.asString() + " was expected, but is not present")));
}
 
Example #29
Source File: NFAAnalysisTools.java    From RegexStaticAnalysis with MIT License 5 votes vote down vote up
/**
 * Constructs a list of NFA graphs each representing a strongly connected
 * component in the graph given as parameter.
 * 
 * @param m
 *            The NFA graph to find the strongly connected components in.
 * @return A list containing all the strongly connected components.
 * @throws InterruptedException 
 */
public static LinkedList<NFAGraph> getStronglyConnectedComponents(NFAGraph m) throws InterruptedException {
	KosarajuStrongConnectivityInspector<NFAVertexND, NFAEdge> sci = new KosarajuStrongConnectivityInspector<NFAVertexND, NFAEdge>(m);
	List<Graph<NFAVertexND, NFAEdge>> sccs = sci.getStronglyConnectedComponents();
	LinkedList<NFAGraph> sccNFAs = new LinkedList<NFAGraph>();

	for (Graph<NFAVertexND, NFAEdge> scc : sccs) {
		if (isInterrupted()) {
			throw new InterruptedException();
		}

		/* scc's consisting of no edges are irrelevant for our purpose */
		if (scc.edgeSet().size() > 0) {

			NFAGraph currentNFAG = new NFAGraph();
			for (NFAVertexND v : scc.vertexSet()) {
				if (isInterrupted()) {
					throw new InterruptedException();
				}
				currentNFAG.addVertex(v);
			}
			for (NFAEdge e : scc.edgeSet()) {
				if (isInterrupted()) {
					throw new InterruptedException();
				}
				currentNFAG.addEdge(e);
			}

			sccNFAs.add(currentNFAG);
		}

	}
	return sccNFAs;
}
 
Example #30
Source File: GraphFunctions.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert a graph into an IExpr object.
 * 
 * @param g
 * @return
 */
public static IExpr graphToIExpr(AbstractBaseGraph<IExpr, ExprEdge> g) {
	IASTAppendable vertexes = vertexToIExpr(g);
	IASTAppendable[] edgeData = edgesToIExpr(g);
	if (edgeData[1] == null) {
		return F.Graph(vertexes, edgeData[0]);
	}
	return F.Graph(vertexes, edgeData[0], F.List(F.Rule(F.EdgeWeight, edgeData[1])));
}