org.jgrapht.GraphPath Java Examples

The following examples show how to use org.jgrapht.GraphPath. 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: ShortestPathPointRouter.java    From openAGV with Apache License 2.0 6 votes vote down vote up
@Override
public long getCosts(TCSObjectReference<Point> srcPointRef,
                     TCSObjectReference<Point> destPointRef) {
  requireNonNull(srcPointRef, "srcPointRef");
  requireNonNull(destPointRef, "destPointRef");

  if (Objects.equals(srcPointRef.getName(), destPointRef.getName())) {
    return 0;
  }

  GraphPath<String, ModelEdge> graphPath = algo.getPath(srcPointRef.getName(),
                                                        destPointRef.getName());
  if (graphPath == null) {
    return INFINITE_COSTS;
  }

  return (long) graphPath.getWeight();
}
 
Example #2
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 #3
Source File: PathInspectorTestCase.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public void testBuildGraph() {

		Relationship r3 = new Relationship();
		r3.setSourceFields(entities.get(0).getAllFields());
		r3.setTargetFields(entities.get(2).getAllFields());
		List<Relationship> edges = new ArrayList<Relationship>();
		edges.add(r3);
		
		List<GraphPath<IModelEntity, Relationship>> paths = new ArrayList<GraphPath<IModelEntity, Relationship>>();
		GraphPath<IModelEntity, Relationship> path = new GraphPathImpl<IModelEntity, Relationship>(graph, entities.get(0), entities.get(2), edges, 9.0);
		paths.add(path);
		
		
		QueryGraphBuilder qgb = new QueryGraphBuilder();
	//	UndirectedGraph<IModelEntity, Relationship> graph = qgb.buildGraph(paths);
		
	}
 
Example #4
Source File: PathInspector.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get all the paths passing from the passed vertex
 * @param vertex 
 * @return
 */
private Set<GraphPath<IModelEntity, Relationship>> getPathsOfAmbigousEntities(IModelEntity vertex){
	logger.debug("IN");
	logger.debug("Getting all the paths passing through the vertex "+vertex.getName());
	Iterator<GraphPath<IModelEntity, Relationship>> iter = getAllGraphPaths().iterator();
	Set<GraphPath<IModelEntity, Relationship>> toReturn = new HashSet<GraphPath<IModelEntity,Relationship>>();
	while(iter.hasNext()){
		GraphPath<IModelEntity, Relationship> path = iter.next();
		if(containsVertex(path, vertex)){
			toReturn.add(path);
		}
	}
	logger.debug("The path passing through the vertex are "+toReturn.size());
	logger.debug("OUT");
	return toReturn;
}
 
Example #5
Source File: SimpleRoadMapPlanner.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get the shortest path connecting given locations (two or more). The path between successive pairs of locations
 * is computed with Dijkstra's algorithm, where edge weights are path lengths.
 * @param locations At least two location names.
 * @return The shortest path connecting given locations.
 */
public PoseSteering[] getShortestPath(String[] locations) {
	if (locations.length < 2) throw new Error("Please provide at least two locations for path extraction!");
	DijkstraShortestPath<String, DefaultWeightedEdge> dijkstraShortestPath = new DijkstraShortestPath<String, DefaultWeightedEdge>(graph);
	ArrayList<PoseSteering> overallShortestPath = new ArrayList<PoseSteering>();
	for (int k = 0; k < locations.length-1; k++) {
	    GraphPath<String, DefaultWeightedEdge> gp = dijkstraShortestPath.getPath(locations[k], locations[k+1]);			
	    if (gp == null) return null;
	    List<String> oneShortestPath = gp.getVertexList();
	    ArrayList<PoseSteering> allPoses = new ArrayList<PoseSteering>();
	    for (int i = 0; i < oneShortestPath.size()-1; i++) {
	    	//PoseSteering[] onePath = loadKnownPath(oneShortestPath.get(i),oneShortestPath.get(i+1));
	    	PoseSteering[] onePath = paths.get(oneShortestPath.get(i)+"->"+oneShortestPath.get(i+1));
	    	if (i == 0) allPoses.add(onePath[0]);
	    	for (int j = 1; j < onePath.length-1; j++) {
	    		allPoses.add(onePath[j]);
	    	}
	    	if (i == oneShortestPath.size()-2) allPoses.add(onePath[onePath.length-1]);
	    }
	    if (k == 0) overallShortestPath.add(allPoses.get(0));
	    for (int i = 1; i < allPoses.size(); i++) {
	    	overallShortestPath.add(allPoses.get(i));
	    }
	}
	return overallShortestPath.toArray(new PoseSteering[overallShortestPath.size()]);
}
 
Example #6
Source File: Missions.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get the shortest path connecting given locations (two or more). The path between successive pairs of locations
 * is computed with Dijkstra's algorithm, where edge weights are path lengths.
 * @param locations At least two location names.
 * @return The shortest path connecting given locations.
 */
public static PoseSteering[] getShortestPath(String ... locations) {
	if (locations.length < 2) throw new Error("Please provide at least two locations for path extraction!");
	DijkstraShortestPath<String, DefaultWeightedEdge> dijkstraShortestPath = new DijkstraShortestPath<String, DefaultWeightedEdge>(graph);
	ArrayList<PoseSteering> overallShortestPath = new ArrayList<PoseSteering>();
	for (int k = 0; k < locations.length-1; k++) {
	    GraphPath<String, DefaultWeightedEdge> gp = dijkstraShortestPath.getPath(locations[k], locations[k+1]);			
	    if (gp == null) return null;
	    List<String> oneShortestPath = gp.getVertexList();
	    ArrayList<PoseSteering> allPoses = new ArrayList<PoseSteering>();
	    for (int i = 0; i < oneShortestPath.size()-1; i++) {
	    	//PoseSteering[] onePath = loadKnownPath(oneShortestPath.get(i),oneShortestPath.get(i+1));
	    	PoseSteering[] onePath = paths.get(oneShortestPath.get(i)+"->"+oneShortestPath.get(i+1));
	    	if (i == 0) allPoses.add(onePath[0]);
	    	for (int j = 1; j < onePath.length-1; j++) {
	    		allPoses.add(onePath[j]);
	    	}
	    	if (i == oneShortestPath.size()-2) allPoses.add(onePath[onePath.length-1]);
	    }
	    if (k == 0) overallShortestPath.add(allPoses.get(0));
	    for (int i = 1; i < allPoses.size(); i++) {
	    	overallShortestPath.add(allPoses.get(i));
	    }
	}
	return overallShortestPath.toArray(new PoseSteering[overallShortestPath.size()]);
}
 
Example #7
Source File: PathInspector.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the map where the key are ambiguous Entities and the values
 * are all the paths that pass through the ambiguous entities 
 * @return
 */
public  Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> getAllEntitiesPathsMap(){
	logger.debug("IN");
	Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> ambiguouPathsMap = new HashMap<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >>();

	Iterator<IModelEntity> iter = entities.iterator();

	//add the paths to the ambiguous path map
	while(iter.hasNext()){
		IModelEntity entity = iter.next();
		
		Set<GraphPath<IModelEntity, Relationship>> 	pathsInvolvingEntity = getPathsOfAmbigousEntities(entity);
		ambiguouPathsMap.put(entity, pathsInvolvingEntity);
	} 

	logger.debug("OUT");
	return ambiguouPathsMap;
}
 
Example #8
Source File: GamaGraph.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public IList<IList<E>> computeKBestRoutesBetween(final IScope scope, final V source, final V target, final int k) {
	final Pair<V, V> pp = new Pair<>(source, target);
	final IList<IList<E>> paths = GamaListFactory.create(Types.LIST.of(getGamlType().getContentType()));
	final IList<IList<E>> sps = shortestPathComputed.get(pp);
	if (sps != null && sps.size() >= k) {
		for (final IList<E> sp : sps) {
			paths.add(GamaListFactory.create(scope, getGamlType().getContentType(), sp));
		}
	} else {
		final KShortestPaths<V, E> kp = new KShortestPaths<>(getProxyGraph(), k);

		final List<GraphPath<V, E>> pathsJGT = kp.getPaths(source, target);
		final IList<IList<E>> el = GamaListFactory.create(Types.LIST.of(getGamlType().getContentType()));
		for (final GraphPath<V, E> p : pathsJGT) {
			paths.add(GamaListFactory.create(scope, getGamlType().getContentType(), p.getEdgeList()));
			if (saveComputedShortestPaths) {
				el.add(GamaListFactory.create(scope, getGamlType().getContentType(), p.getEdgeList()));
			}
		}
		if (saveComputedShortestPaths) {
			shortestPathComputed.put(pp, el);
		}
	}
	return paths;
}
 
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 {
		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 = eulerianCycle(g);
			if (path != null) {
				// Graph is Eulerian
				return F.True;
			}
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.False;
}
 
Example #10
Source File: QbeQueryResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * @param filteredQuery
 * @param modelFields
 */
private List<GraphPath<IModelEntity, Relationship>> getShortestPaths(Query filteredQuery, IModelEntity modelEntity) {
	List<GraphPath<IModelEntity, Relationship>> shortestPaths = new ArrayList<>();
	Set<GraphPath<IModelEntity, Relationship>> modelEntityPaths = getModelEntityPaths(filteredQuery, modelEntity);
	if (modelEntityPaths != null) {
		for (GraphPath<IModelEntity, Relationship> path : modelEntityPaths) {

			if (!shortestPaths.isEmpty() && path.getWeight() == shortestPaths.get(shortestPaths.size() - 1).getWeight()) {
				shortestPaths.add(path);
			} else if (!shortestPaths.isEmpty() && path.getWeight() < shortestPaths.get(shortestPaths.size() - 1).getWeight()) {
				shortestPaths.clear();
				shortestPaths.add(path);
			} else if (shortestPaths.isEmpty()) {
				shortestPaths.add(path);
			}

		}
	}

	return shortestPaths;
}
 
Example #11
Source File: ShortestPathPointRouter.java    From openAGV with Apache License 2.0 6 votes vote down vote up
private List<Route.Step> translateToSteps(GraphPath<String, ModelEdge> graphPath) {
  List<ModelEdge> edges = graphPath.getEdgeList();
  List<Route.Step> result = new ArrayList<>(edges.size());

  int routeIndex = 0;
  for (ModelEdge edge : edges) {
    Point sourcePoint = points.get(graphPath.getGraph().getEdgeSource(edge));
    Point destPoint = points.get(graphPath.getGraph().getEdgeTarget(edge));

    result.add(new Route.Step(edge.getModelPath(),
                              sourcePoint,
                              destPoint,
                              orientation(edge, sourcePoint),
                              routeIndex));
    routeIndex++;
  }

  return result;
}
 
Example #12
Source File: ShortestPathPointRouter.java    From openAGV with Apache License 2.0 6 votes vote down vote up
@Override
public List<Route.Step> getRouteSteps(Point srcPoint, Point destPoint) {
  requireNonNull(srcPoint, "srcPoint");
  requireNonNull(destPoint, "destPoint");

  long timeBefore = System.currentTimeMillis();
  if (Objects.equals(srcPoint.getName(), destPoint.getName())) {
    return new ArrayList<>();
  }

  //TODO 占用的点不再用,难道要在这里每次都new一个新的algo ??
  GraphPath<String, ModelEdge> graphPath = algo.getPath(srcPoint.getName(), destPoint.getName());
  if (graphPath == null) {
    return null;
  }

  List<Route.Step> result = translateToSteps(graphPath);

  LOG.debug("Looking up route from {} to {} took {} milliseconds.",
            srcPoint.getName(),
            destPoint.getName(),
            System.currentTimeMillis() - timeBefore);

  return result;
}
 
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 {
		GraphExpr<ExprEdge> gex = createGraph(ast.arg1());
		if (gex == null) {
			return F.NIL;
		}

		Graph<IExpr, ExprEdge> g = gex.toData();

		DijkstraShortestPath<IExpr, ExprEdge> dijkstraAlg = new DijkstraShortestPath<>(g);
		SingleSourcePaths<IExpr, ExprEdge> iPaths = dijkstraAlg.getPaths(ast.arg2());
		GraphPath<IExpr, ExprEdge> path = iPaths.getPath(ast.arg3());

		return Object2Expr.convertList(path.getVertexList());
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #14
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 #15
Source File: RootEntitiesGraph.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public Set<Relationship> getConnectingRelatiosnhips(Set<IModelEntity> entities) {

		Set<Relationship> connectingRelatiosnhips = new HashSet<Relationship>();

		Set<IModelEntity> connectedEntities = new HashSet<IModelEntity>();

		Iterator<IModelEntity> it = entities.iterator();
		connectedEntities.add(it.next());

		while (it.hasNext()) {
			IModelEntity entity = it.next();
			if (connectedEntities.contains(entity))
				continue;
			GraphPath minimumPath = null;
			double minPathLength = Double.MAX_VALUE;
			for (IModelEntity connectedEntity : connectedEntities) {
				DijkstraShortestPath dsp = new DijkstraShortestPath(rootEntitiesGraph, entity, connectedEntity);
				double pathLength = dsp.getPathLength();
				if (minPathLength > pathLength) {
					minPathLength = pathLength;
					minimumPath = dsp.getPath();
				}
			}
			List<Relationship> relationships = minimumPath.getEdgeList();
			connectingRelatiosnhips.addAll(relationships);
			for (Relationship relatioship : relationships) {
				connectedEntities.add(rootEntitiesGraph.getEdgeSource(relatioship));
				connectedEntities.add(rootEntitiesGraph.getEdgeTarget(relatioship));
			}
		}

		for (Relationship r : connectingRelatiosnhips) {
			IModelEntity source = rootEntitiesGraph.getEdgeSource(r);
			IModelEntity target = rootEntitiesGraph.getEdgeTarget(r);
			logger.error(source.getName() + " -> " + target.getName());
		}

		return connectingRelatiosnhips;
	}
 
Example #16
Source File: DefaultTermGraph.java    From cocolian-nlp with Apache License 2.0 5 votes vote down vote up
@Override
public TermPath createPath(GraphPath<POSTerm, TermEdge> path) {
	TermPath termPath = this.createPath(path.getStartVertex());
	for (TermEdge edge : path.getEdgeList())
		termPath.extend(edge);
	return termPath;

}
 
Example #17
Source File: PathInspector.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param path
 * @param vertex
 * @return
 */
private boolean containsVertex(GraphPath<IModelEntity,Relationship> path, IModelEntity vertex){
	List<Relationship> edges = path.getEdgeList();
	for (int i = 0; i < edges.size(); i++) {
		Relationship r =(Relationship) edges.get(i);
		if(r.getSourceEntity().equals(vertex) || r.getTargetEntity().equals(vertex) ){
			return true;
		}
	}
	return false;
}
 
Example #18
Source File: QueryGraphBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addPathToGraph(Graph<IModelEntity, Relationship> graph, GraphPath<IModelEntity, Relationship> path ){
	logger.debug("IN");
	List<Relationship> edges = path.getEdgeList();
	if(edges!=null){
		for(int i=0; i<edges.size(); i++){
			Relationship edge = (Relationship)edges.get(i);
			addEdgeToGraph(graph, edge);
		}
	}
	logger.debug("OUT");
}
 
Example #19
Source File: PathInspector.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Gets the map where the key are ambiguous Entities and the values
 * are all the paths that pass through the ambiguous entities 
 * @return
 */
public  Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> getAmbiguousEntitiesAllPathsMap(){
	logger.debug("IN");
	Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >> ambiguouPathsMap = new HashMap<IModelEntity, Set<GraphPath<IModelEntity, Relationship> >>();
	Set<EntitiesPath> ambiguouPaths = getAmbiguousEntitiesPaths();
	if(ambiguouPaths!=null){
		Iterator<EntitiesPath> iter = ambiguouPaths.iterator();

		//add the paths to the ambiguous path map
		while(iter.hasNext()){
			EntitiesPath entitiesPath = iter.next();
			Set<GraphPath<IModelEntity, Relationship>> pathsInvolvingStartEntity;
			if(!ambiguouPathsMap.containsKey(entitiesPath.getEndPoints().get(0))){
				pathsInvolvingStartEntity = getPathsOfAmbigousEntities(entitiesPath.getEndPoints().get(0));
				ambiguouPathsMap.put(entitiesPath.getEndPoints().get(0), pathsInvolvingStartEntity);
			}

			Set<GraphPath<IModelEntity, Relationship>> pathsInvolvingEndEntity;
			if(!ambiguouPathsMap.containsKey(entitiesPath.getEndPoints().get(1))){
				pathsInvolvingEndEntity = getPathsOfAmbigousEntities(entitiesPath.getEndPoints().get(1));
				ambiguouPathsMap.put(entitiesPath.getEndPoints().get(1), pathsInvolvingEndEntity);
			}
		} 
	}
	logger.debug("OUT");
	return ambiguouPathsMap;
}
 
Example #20
Source File: ShortestPathsCoverGraph.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship>>> getConnectingRelatiosnhips(QueryGraph monimumGraph, Set<IModelEntity> entities) {
	PathInspector pi = new PathInspector(monimumGraph, monimumGraph.vertexSet());
	Map<IModelEntity, Set<GraphPath<IModelEntity, Relationship>>> minimumPaths = pi.getAllEntitiesPathsMap();

	return minimumPaths;
}
 
Example #21
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 #22
Source File: ModelFieldPaths.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public ModelFieldPaths(IQueryField queryField, IModelField field, Set<GraphPath<IModelEntity, Relationship>> paths ){
	this(field, queryField);

	choices = new HashSet<PathChoice>();
	if(paths!=null){
		Iterator<GraphPath<IModelEntity, Relationship>> pathsiter = paths.iterator();
		while (pathsiter.hasNext()) {
			choices.add(new PathChoice(pathsiter.next()));
		}
	}
}
 
Example #23
Source File: PathChoice.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@JsonIgnore
public boolean isTheSamePath(GraphPath<IModelEntity, Relationship> path2){
	if(path == null){
		return false;
	}
	return GraphUtilities.arePathsEquals(path, path2);
}
 
Example #24
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();
			GraphPath<IExpr, ExprEdge> path = eulerianCycle(g);
			if (path == null) {
				// Graph is not Eulerian
				return F.CEmptyList;
			}
			List<IExpr> iList = path.getVertexList();
			IASTAppendable list = F.ListAlloc(iList.size());
			for (int i = 0; i < iList.size() - 1; i++) {
				list.append(F.DirectedEdge(iList.get(i), iList.get(i + 1)));
			}
			return list;
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #25
Source File: GraphUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Set<String> getRelationsSet(GraphPath<IModelEntity, Relationship> path1) {
	Set<String> relations = new HashSet<String>();
	List<Relationship> edges = path1.getEdgeList();
	for (int i = 0; i < edges.size(); i++) {
		relations.add(edges.get(i).getId());
	}
	return relations;

}
 
Example #26
Source File: DirectedGraphUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() {
    StrongConnectivityAlgorithm<String, DefaultEdge> scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph);
    List<DirectedSubgraph<String, DefaultEdge>> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs();
    List<String> stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet());

    String randomVertex1 = stronglyConnectedVertices.get(0);
    String randomVertex2 = stronglyConnectedVertices.get(3);
    AllDirectedPaths<String, DefaultEdge> allDirectedPaths = new AllDirectedPaths<>(directedGraph);

    List<GraphPath<String, DefaultEdge>> possiblePathList = allDirectedPaths.getAllPaths(randomVertex1, randomVertex2, false, stronglyConnectedVertices.size());
    assertTrue(possiblePathList.size() > 0);
}
 
Example #27
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 #28
Source File: RepresentationsGraph.java    From DDF with Apache License 2.0 5 votes vote down vote up
public GraphPath<Representation, ConvertFunction> getShortestPath(Representation startVertex,
    Representation endVertex) {
  try {
    return new DijkstraShortestPath<Representation, ConvertFunction>(this.mGraph, startVertex, endVertex).getPath();
  } catch (Exception e) {
    return null;
  }
}
 
Example #29
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();
			GraphPath<IExpr, ExprEdge> path = hamiltonianCycle(g);
			if (path == null) {
				// Graph is not Hamiltonian
				return F.CEmptyList;
			}
			List<IExpr> iList = path.getVertexList();
			IASTAppendable list = F.ListAlloc(iList.size());
			for (int i = 0; i < iList.size() - 1; i++) {
				list.append(F.DirectedEdge(iList.get(i), iList.get(i + 1)));
			}
			return list;
		}
	} catch (RuntimeException rex) {
		if (FEConfig.SHOW_STACKTRACE) {
			rex.printStackTrace();
		}
	}
	return F.NIL;
}
 
Example #30
Source File: ShortestPath.java    From waltz with Apache License 2.0 5 votes vote down vote up
private static GraphPath<EntityReference, DefaultEdge> findShortestPath(Graph<EntityReference, DefaultEdge> g, EntityReference start, EntityReference end) {
    DijkstraShortestPath<EntityReference, DefaultEdge> dijkstraAlg =
            new DijkstraShortestPath<>(g);

    SingleSourcePaths<EntityReference, DefaultEdge> iPaths = dijkstraAlg.getPaths(start);
    return iPaths.getPath(end);
}