org.jgrapht.graph.DefaultWeightedEdge Java Examples

The following examples show how to use org.jgrapht.graph.DefaultWeightedEdge. 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: SimpleRoadMapPlanner.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
private void buildGraphs() {
	this.graph = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
	
	metaCSPLogger.info("Updating the roadmap with the given graph ...");
	
	for (String v : locations.keySet()) {
		this.graph.addVertex(v);
		metaCSPLogger.info("Added vertex " + v + ".");
	}
	
	for (String from : locations.keySet()) {
		for (String to : locations.keySet()) {
			if (!from.equals(to)) {
				if (paths.containsKey(from+"->"+to)) {
					PoseSteering[] path = paths.get(from+"->"+to);
					DefaultWeightedEdge e = addEdge(graph, from, to, (double)path.length);
					metaCSPLogger.info("Added edge " + e);
				}
			}
		}	
	}
}
 
Example #2
Source File: SteinerTreeTest.java    From jReto with MIT License 6 votes vote down vote up
@Test
public void testTrivial() {
	DirectedWeightedPseudograph<Integer, DefaultWeightedEdge> graph = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
	
	graph.addVertex(1);
	graph.addVertex(2);
	graph.addVertex(3);
	
	addSymmetricEdge(graph, 1, 2, 10);
	addSymmetricEdge(graph, 2, 3, 10);
	
	Tree<Integer> tree = MinimumSteinerTreeApproximation.approximateSteinerTree(graph, 1, new HashSet<>(Arrays.asList(1,2,3)));
	
	Tree<Integer> expectedResult = 
		new Tree<>(1, 
			new Tree<>(2, 
				new Tree<>(3)
			)
		);
	
	assertTrue("Did not get expected result.", tree.equals(expectedResult));
}
 
Example #3
Source File: LinkStateRoutingTable.java    From jReto with MIT License 6 votes vote down vote up
/** Updates link state information for a given node. */
private void updateLinkStateInformation(T node, List<NeighborInformation<T>> neighbors) {
	// Remove all edges
	if (this.graph.vertexSet().contains(node)) {
		Set<DefaultWeightedEdge> outgoingEdges = new HashSet<>(this.graph.outgoingEdgesOf(node));
		this.graph.removeAllEdges(outgoingEdges);
	} else {
		this.graph.addVertex(node);
	}

	// Add new edges
	for (NeighborInformation<T> neighbor : neighbors) {
		this.graph.addVertex(neighbor.node);
		DefaultWeightedEdge edge = this.graph.addEdge(node, neighbor.node);
		this.graph.setEdgeWeight(edge, neighbor.cost);
	}
}
 
Example #4
Source File: BAPTSPTest.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a TSPLib tour to a set of columns: A column for every pricing problem is created
 * @param tour tour
 * @param pricingProblems pricing problems
 * @return List of columns
 */
private List<Matching> convertTourToColumns(TSP tsp, TSPLibTour tour, List<PricingProblemByColor> pricingProblems) {
	List<Set<DefaultWeightedEdge>> matchings=new ArrayList<>();
	matchings.add(new LinkedHashSet<>());
	matchings.add(new LinkedHashSet<>());

	int color=0;
	for(int index=0; index<tsp.N; index++){
		int i=tour.get(index);
		int j=tour.get((index + 1) % tsp.N);
		DefaultWeightedEdge edge = tsp.getEdge(i, j);
		matchings.get(color).add(edge);
		color=(color+1)%2;
	}

	List<Matching> initSolution=new ArrayList<>();
	initSolution.add(this.buildMatching(tsp, pricingProblems.get(0), matchings.get(0)));
	initSolution.add(this.buildMatching(tsp, pricingProblems.get(1), matchings.get(1)));
	return initSolution;
}
 
Example #5
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Checks whether there are any violated inequalities, thereby invoking the cut handler
 * @return true if violated inqualities have been found (and added to the master problem)
 */
@Override
public boolean hasNewCuts(){
	//For convenience, we will precompute values required by the SubtourInequalityGenerator class
	//and store it in the masterData object. For each edge, we need to know how often it is used.
	masterData.edgeValueMap.clear();
	for(Matching matching : this.getSolution()){
		for(DefaultWeightedEdge edge : matching.edges){
			if(masterData.edgeValueMap.containsKey(edge))
				masterData.edgeValueMap.put(edge, masterData.edgeValueMap.get(edge)+matching.value);
			else
				masterData.edgeValueMap.put(edge,matching.value);
		}
	}
	return super.hasNewCuts();
}
 
Example #6
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Extracts information from the master problem which is required by the pricing problems, e.g. the reduced costs/dual values
 * @param pricingProblem pricing problem
 */
@Override
public void initializePricingProblem(PricingProblemByColor pricingProblem) {
	try {
		double[] modifiedCosts=new double[dataModel.N*(dataModel.N-1)/2]; //Modified cost for every edge
		int index=0;
		for(DefaultWeightedEdge edge : dataModel.edgeSet()){
			modifiedCosts[index]=masterData.cplex.getDual(edgeOnlyUsedOnceConstr.get(edge))- dataModel.getEdgeWeight(edge);
			for(SubtourInequality subtourInequality : masterData.subtourInequalities.keySet()){
				if(subtourInequality.cutSet.contains(dataModel.getEdgeSource(edge)) ^ subtourInequality.cutSet.contains(dataModel.getEdgeTarget(edge)))
					modifiedCosts[index]+= masterData.cplex.getDual(masterData.subtourInequalities.get(subtourInequality));
			}
			index++;
		}
		double dualConstant;
		if(pricingProblem.color== MatchingColor.RED)
			dualConstant=masterData.cplex.getDual(exactlyOneRedMatchingConstr);
		else
			dualConstant=masterData.cplex.getDual(exactlyOneBlueMatchingConstr);

		pricingProblem.initPricingProblem(modifiedCosts, dualConstant);
	} catch (IloException e) {
		e.printStackTrace();
	}
}
 
Example #7
Source File: TSPSolver.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a TSPLib tour to a set of columns: A column for every pricing problem is created
 * @param tour tour
 * @param pricingProblems pricing problems
 * @return List of columns
 */
private List<Matching> convertTourToColumns(TSPLibTour tour, List<PricingProblemByColor> pricingProblems) {
	List<Set<DefaultWeightedEdge>> matchings=new ArrayList<>();
	matchings.add(new LinkedHashSet<>());
	matchings.add(new LinkedHashSet<>());

	int color=0;
	for(int index=0; index<tsp.N; index++){
		int i=tour.get(index);
		int j=tour.get((index + 1) % tsp.N);
		DefaultWeightedEdge edge = tsp.getEdge(i, j);
		matchings.get(color).add(edge);
		color=(color+1)%2;
	}

	List<Matching> initSolution=new ArrayList<>();
	initSolution.add(this.buildMatching(pricingProblems.get(0), matchings.get(0)));
	initSolution.add(this.buildMatching(pricingProblems.get(1), matchings.get(1)));
	return initSolution;
}
 
Example #8
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Checks whether there are any violated inequalities, thereby invoking the cut handler
 * @return true if violated inqualities have been found (and added to the master problem)
 */
@Override
public boolean hasNewCuts(){
	//For convenience, we will precompute values required by the SubtourInequalityGenerator class
	//and store it in the masterData object. For each edge, we need to know how often it is used.
	masterData.edgeValueMap.clear();
	for(Matching matching : this.getSolution()){
		for(DefaultWeightedEdge edge : matching.edges){
			if(masterData.edgeValueMap.containsKey(edge))
				masterData.edgeValueMap.put(edge, masterData.edgeValueMap.get(edge)+matching.value);
			else
				masterData.edgeValueMap.put(edge,matching.value);
		}
	}
	return super.hasNewCuts();
}
 
Example #9
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Extracts information from the master problem which is required by the pricing problems, e.g. the reduced costs/dual values
 * @param pricingProblem pricing problem
 */
@Override
public void initializePricingProblem(PricingProblemByColor pricingProblem) {
	try {
		double[] modifiedCosts=new double[dataModel.N*(dataModel.N-1)/2]; //Modified cost for every edge
		int index=0;
		for(DefaultWeightedEdge edge : dataModel.edgeSet()){
			modifiedCosts[index]=masterData.cplex.getDual(edgeOnlyUsedOnceConstr.get(edge))- dataModel.getEdgeWeight(edge);
			for(SubtourInequality subtourInequality : masterData.subtourInequalities.keySet()){
				if(subtourInequality.cutSet.contains(dataModel.getEdgeSource(edge)) ^ subtourInequality.cutSet.contains(dataModel.getEdgeTarget(edge)))
					modifiedCosts[index]+= masterData.cplex.getDual(masterData.subtourInequalities.get(subtourInequality));
			}
			index++;
		}
		double dualConstant;
		if(pricingProblem.color==MatchingColor.RED)
			dualConstant=masterData.cplex.getDual(exactlyOneRedMatchingConstr);
		else
			dualConstant=masterData.cplex.getDual(exactlyOneBlueMatchingConstr);

		pricingProblem.initPricingProblem(modifiedCosts, dualConstant);
	} catch (IloException e) {
		e.printStackTrace();
	}
}
 
Example #10
Source File: TSPCGSolver.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a TSPLib tour to a set of columns: A column for every pricing problem is created
 * @param tour tour
 * @param pricingProblems pricing problems
 * @return List of columns
 */
private List<Matching> convertTourToColumns(TSPLibTour tour, List<PricingProblemByColor> pricingProblems) {
	List<Set<DefaultWeightedEdge>> matchings=new ArrayList<>();
	matchings.add(new LinkedHashSet<>());
	matchings.add(new LinkedHashSet<>());

	int color=0;
	for(int index=0; index<tsp.N; index++){
		int i=tour.get(index);
		int j=tour.get((index + 1) % tsp.N);
		DefaultWeightedEdge edge = tsp.getEdge(i, j);
		matchings.get(color).add(edge);
		color=(color+1)%2;
	}

	List<Matching> initSolution=new ArrayList<>();
	initSolution.add(this.buildMatching(pricingProblems.get(0), matchings.get(0)));
	initSolution.add(this.buildMatching(pricingProblems.get(1), matchings.get(1)));
	return initSolution;
}
 
Example #11
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Checks whether there are any violated inequalities, thereby invoking the cut handler
 * @return true if violated inequalities have been found (and added to the master problem)
 */
@Override
public boolean hasNewCuts(){
	//For convenience, we will precompute values required by the SubtourInequalityGenerator class
	//and store it in the masterData object. For each edge, we need to know how often it is used.
	masterData.edgeValueMap.clear();
	for(Matching matching : this.getSolution()){
		for(DefaultWeightedEdge edge : matching.edges){
			if(masterData.edgeValueMap.containsKey(edge))
				masterData.edgeValueMap.put(edge, masterData.edgeValueMap.get(edge)+matching.value);
			else
				masterData.edgeValueMap.put(edge,matching.value);
		}
	}
	return super.hasNewCuts();
}
 
Example #12
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Extracts information from the master problem which is required by the pricing problems, e.g. the reduced costs/dual values
 * @param pricingProblem pricing problem
 */
@Override
public void initializePricingProblem(PricingProblemByColor pricingProblem) {
	try {
		double[] modifiedCosts=new double[dataModel.N*(dataModel.N-1)/2]; //Modified cost for every edge
		int index=0;
		for(DefaultWeightedEdge edge : dataModel.edgeSet()){
			modifiedCosts[index]=masterData.cplex.getDual(edgeOnlyUsedOnceConstr.get(edge))- dataModel.getEdgeWeight(edge);
			for(SubtourInequality subtourInequality : masterData.subtourInequalities.keySet()){
				if(subtourInequality.cutSet.contains(dataModel.getEdgeSource(edge)) ^ subtourInequality.cutSet.contains(dataModel.getEdgeTarget(edge)))
					modifiedCosts[index]+= masterData.cplex.getDual(masterData.subtourInequalities.get(subtourInequality));
			}
			index++;
		}
		double dualConstant;
		if(pricingProblem.color==MatchingColor.RED)
			dualConstant=masterData.cplex.getDual(exactlyOneRedMatchingConstr);
		else
			dualConstant=masterData.cplex.getDual(exactlyOneBlueMatchingConstr);

		pricingProblem.initPricingProblem(modifiedCosts, dualConstant);
	} catch (IloException e) {
		e.printStackTrace();
	}
}
 
Example #13
Source File: GroupLinkage.java    From JedAIToolkit with Apache License 2.0 6 votes vote down vote up
private SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> getSimilarityGraph(Queue<SimilarityEdge> seQueue) {
    final SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> graph = new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
    while (seQueue.size() > 0) {
        SimilarityEdge se = seQueue.remove();
        int i = se.getModel1Pos();
        int j = se.getModel2Pos();
        String label1 = "a" + i;
        String label2 = "b" + j;
        if (!(graph.containsVertex(label1) || graph.containsVertex(label2))) {//only if both vertices don't exist
            graph.addVertex(label1);
            graph.addVertex(label2);
            DefaultWeightedEdge e = graph.addEdge(label1, label2);
            graph.setEdgeWeight(e, se.getSimilarity());
        }
    }

    return graph;
}
 
Example #14
Source File: CutClustering.java    From JedAIToolkit with Apache License 2.0 6 votes vote down vote up
@Override
public EquivalenceCluster[] getDuplicates(SimilarityPairs simPairs) {
    initializeData(simPairs);
    similarityGraph = null;
    initializeGraph();

    final Iterator<Comparison> iterator = simPairs.getPairIterator();
    while (iterator.hasNext()) {	// add an edge for every pair of entities with a weight higher than the threshold
        Comparison comparison = iterator.next();
        if (threshold < comparison.getUtilityMeasure()) {
            DefaultWeightedEdge e = (DefaultWeightedEdge) weightedGraph.addEdge(comparison.getEntityId1() + "", (comparison.getEntityId2() + datasetLimit) + "");
            weightedGraph.setEdgeWeight(e, comparison.getUtilityMeasure());
        }
    }

    GomoryHuTree ght = new GomoryHuTree(weightedGraph); //take the minimum cut (Gomory-Hu) tree from the similarity graph
    duplicatesGraph = ght.MinCutTree();
    duplicatesGraph.removeVertex(noOfEntities); //remove the artificial sink

    return getConnectedComponents();
}
 
Example #15
Source File: Missions.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
private static void buildGraph() {
	
	graph = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
	
	metaCSPLogger.info("Updating the roadmap...");
	
	for (String oneLoc : locations.keySet()) {
		graph.addVertex(oneLoc);
		metaCSPLogger.info("Added vertex " + oneLoc);
	}
	
	for (String from : locations.keySet()) {
		for (String to : locations.keySet()) {
			if (!from.equals(to)) {
				if (isKnownPath(from, to)) {
					DefaultWeightedEdge e = graph.addEdge(from, to);
					//PoseSteering[] path = loadKnownPath(from, to);
					PoseSteering[] path = paths.get(from+"->"+to);
					graph.setEdgeWeight(e, path.length);
					metaCSPLogger.info("Added edge " + e);
				}
			}
		}	
	}
}
 
Example #16
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 #17
Source File: SimpleRoadMapPlanner.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized void clearObstacles() {
	
	if (this.noMap) this.om = null;
	else this.om.clearObstacles();
	
	//Restore the original graph
	if (removedVertices.isEmpty() && removedEdges.isEmpty()) return;
	this.graph = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
	
	//Tracking changes
	for (String v : removedVertices) this.graph.addVertex(v);
	for (DefaultWeightedEdge e : removedEdges.keySet()) {
		DefaultWeightedEdge e1 = this.graph.addEdge(removedEdges.get(e).getSource(),removedEdges.get(e).getTarget());
		this.graph.setEdgeWeight(e1, removedEdges.get(e).getWeight());
	}
	removedVertices.clear();
	removedEdges.clear();
}
 
Example #18
Source File: SimpleRoadMapPlanner.java    From coordination_oru with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AbstractMotionPlanner getCopy() {
	SimpleRoadMapPlanner ret = new SimpleRoadMapPlanner();
	ret.setFootprint(this.footprintCoords);
	ret.om = this.om;
	ret.locations.putAll(this.locations);
	ret.paths.putAll(this.paths);
	ret.removedVertices.addAll(this.removedVertices);
	ret.removedEdges.putAll(this.removedEdges);
	ret.graph = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
	for (String v : this.graph.vertexSet()) ret.graph.addVertex(v);
	for (DefaultWeightedEdge e : this.graph.edgeSet()) {
		DefaultWeightedEdge e1 = ret.graph.addEdge(this.graph.getEdgeSource(e),this.graph.getEdgeTarget(e));
		ret.graph.setEdgeWeight(e1, this.graph.getEdgeWeight(e));
	}
	return ret;
}
 
Example #19
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 #20
Source File: LinkStateRoutingTable.java    From jReto with MIT License 5 votes vote down vote up
/** Returns a list of neighbors for the local node (ie. link state information). */
public List<NeighborInformation<T>> getLinkStateInformation() {
	List<NeighborInformation<T>> linkStateInformation = new ArrayList<>();
	
	for (DefaultWeightedEdge edge : this.graph.outgoingEdgesOf(this.localNode)) {
		linkStateInformation.add(new NeighborInformation<T>(this.graph.getEdgeTarget(edge), this.graph.getEdgeWeight(edge)));
	}
	
	return linkStateInformation;
}
 
Example #21
Source File: BAPTSPTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Helper method which builds a column for a given pricing problem consisting of the predefined edges
 * @param pricingProblem pricing problem
 * @param edges List of edges constituting the matching
 * @return Matching
 */
private Matching buildMatching(TSP tsp, PricingProblemByColor pricingProblem, Set<DefaultWeightedEdge> edges) {
	int[] succ=new int[tsp.N];

	int cost=0;
	for(DefaultWeightedEdge edge : edges) {
		succ[tsp.getEdgeSource(edge)]=tsp.getEdgeTarget(edge);
		succ[tsp.getEdgeTarget(edge)]=tsp.getEdgeSource(edge);
		cost+=tsp.getEdgeWeight(edge);
	}
	return new Matching("init", false, pricingProblem, edges, succ, cost);
}
 
Example #22
Source File: LinkStateRoutingTable.java    From jReto with MIT License 5 votes vote down vote up
/** Updates or adds a neighbor. */
private void updateNeighbor(T neighbor, double cost) {
	if (this.graph.edgeSet().contains(neighbor)) this.graph.removeAllEdges(this.localNode, neighbor);
	this.graph.addVertex(neighbor);
	DefaultWeightedEdge edge = this.graph.addEdge(this.localNode, neighbor);
	this.graph.setEdgeWeight(edge, cost);
}
 
Example #23
Source File: SteinerTreeTest.java    From jReto with MIT License 5 votes vote down vote up
@Test
public void testTwoClustersMulticast() {
	DirectedWeightedPseudograph<Integer, DefaultWeightedEdge> graph = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
	
	graph.addVertex(1);
	graph.addVertex(2);
	graph.addVertex(3);
	
	graph.addVertex(4);
	graph.addVertex(5);
	graph.addVertex(6);
	
	/**
	 * Imagine two groups, 1,2,3 and 4,5,6, each internally connected via wifi, but 1,2, and 5 have internet access in addition.
	 * */
	addSymmetricEdge(graph, 1, 2, 1);
	addSymmetricEdge(graph, 2, 3, 2);
	addSymmetricEdge(graph, 3, 1, 1);
	
	addSymmetricEdge(graph, 4, 5, 1);
	addSymmetricEdge(graph, 5, 6, 1);
	addSymmetricEdge(graph, 6, 4, 2);
	
	addSymmetricEdge(graph, 1, 5, 10);
	addSymmetricEdge(graph, 2, 5, 11);
	
	Tree<Integer> tree = MinimumSteinerTreeApproximation.approximateSteinerTree(graph, 1, new HashSet<>(Arrays.asList(1,5,6)));

	Tree<Integer> expectedResult =
		new Tree<>(1,
			new Tree<>(5,
				new Tree<>(6)
			)
		);
	
	assertTrue("Did not get expected result.", tree.equals(expectedResult));
}
 
Example #24
Source File: TSP.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
public TSP(InputStream inputStream) throws IOException{
	super(DefaultWeightedEdge.class);
	tspLibInstance= new TSPLibInstance(inputStream);
	this.N=tspLibInstance.getDimension();

	//Create the graph for jGrapht
	for(int i=0; i<tspLibInstance.getDimension()-1; i++){
		for(int j=i+1; j<tspLibInstance.getDimension(); j++){
			Graphs.addEdgeWithVertices(this, i, j, tspLibInstance.getDistanceTable().getDistanceBetween(i, j));
		}
	}
}
 
Example #25
Source File: SubtourInequalityGenerator.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * If a violated inequality has been found add it to the master problem.
 * @param subtourInequality subtour inequality
 */
private void addCut(SubtourInequality subtourInequality){
	if(masterData.subtourInequalities.containsKey(subtourInequality))
		throw new RuntimeException("Error, duplicate subtour cut is being generated! This cut should already exist in the master problem: "+subtourInequality);
	//Create the inequality in cplex
	try {
		IloLinearNumExpr expr=masterData.cplex.linearNumExpr();
		//Register the columns with this constraint.
		for(PricingProblemByColor pricingProblem : masterData.pricingProblems){
			for(Matching matching: masterData.getColumnsForPricingProblemAsList(pricingProblem)){
				//Test how many edges in the matching enter/leave the cutSet (edges with exactly one endpoint in the cutSet)
				int crossings=0;
				for(DefaultWeightedEdge edge: matching.edges){
					if(subtourInequality.cutSet.contains(dataModel.getEdgeSource(edge)) ^ subtourInequality.cutSet.contains(dataModel.getEdgeTarget(edge)))
						crossings++;
				}
				if(crossings>0){
					IloNumVar var=masterData.getVar(pricingProblem,matching);
					expr.addTerm(crossings, var);
				}
			}
		}
		IloRange subtourConstraint = masterData.cplex.addGe(expr, 2, "subtour");
		masterData.subtourInequalities.put(subtourInequality, subtourConstraint);
	} catch (IloException e) {
		e.printStackTrace();
	}
}
 
Example #26
Source File: SimpleRoadMapPlanner.java    From coordination_oru with GNU General Public License v3.0 5 votes vote down vote up
private DefaultWeightedEdge addEdge(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> graph, String source, String target, double weight) {
	graph.addVertex(source);
	graph.addVertex(target);
	DefaultWeightedEdge e = graph.addEdge(source,target);
	graph.setEdgeWeight(e, weight);
	return e;
}
 
Example #27
Source File: SteinerTreeTest.java    From jReto with MIT License 5 votes vote down vote up
@Test
public void testSingleSteinerVertex() {
	DirectedWeightedPseudograph<Integer, DefaultWeightedEdge> graph = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
	
	graph.addVertex(1);
	graph.addVertex(2);
	graph.addVertex(3);
	graph.addVertex(4);
	
	addSymmetricEdge(graph, 1, 2, 10);
	addSymmetricEdge(graph, 2, 3, 10);
	addSymmetricEdge(graph, 3, 1, 10);
	
	addSymmetricEdge(graph, 1, 4, 1);
	addSymmetricEdge(graph, 2, 4, 1);
	addSymmetricEdge(graph, 3, 4, 1);
	
	Tree<Integer> tree = MinimumSteinerTreeApproximation.approximateSteinerTree(graph, 1, new HashSet<>(Arrays.asList(1,2,3)));
	
	Tree<Integer> expectedResult =
		new Tree<>(1, 
			new Tree<>(4, 
				new Tree<>(2), 
				new Tree<>(3)
			)
		);
	
	assertTrue("Did not get expected result.", tree.equals(expectedResult));
}
 
Example #28
Source File: Master.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Builds the master model
 * @return Returns a MasterData object which is a data container for information coming from the master problem
 */
@Override
protected TSPMasterData buildModel() {
	IloCplex cplex=null;

	try {
		cplex=new IloCplex(); //Create cplex instance
		cplex.setOut(null); //Disable cplex output
		cplex.setParam(IloCplex.IntParam.Threads,config.MAXTHREADS); //Set number of threads that may be used by the master

		//Define objective
		obj=cplex.addMinimize();

		//Define constraints
		exactlyOneRedMatchingConstr=cplex.addRange(1, 1, "exactlyOneRed"); //Select exactly one red matching
		exactlyOneBlueMatchingConstr=cplex.addRange(1, 1, "exactlyOneBlue"); //Select exactly one blue matching

		edgeOnlyUsedOnceConstr=new LinkedHashMap<>(); //Each edge may only be used once
		for(DefaultWeightedEdge edge : dataModel.edgeSet()){
			IloRange constr=cplex.addRange(0, 1, "edgeOnlyUsedOnce_"+ dataModel.getEdgeSource(edge)+"_"+ dataModel.getEdgeTarget(edge));
			edgeOnlyUsedOnceConstr.put(edge,  constr);
		}
	} catch (IloException e) {
		e.printStackTrace();
	}

	Map<PricingProblemByColor, OrderedBiMap<Matching, IloNumVar>> varMap=new LinkedHashMap<>();
	for(PricingProblemByColor pricingProblem : pricingProblems)
		varMap.put(pricingProblem, new OrderedBiMap<>());

	//Create a new data object which will store information from the master. This object automatically be passed to the CutHandler class.
	return new TSPMasterData(cplex, pricingProblems, varMap);
}
 
Example #29
Source File: SteinerTreeTest.java    From jReto with MIT License 5 votes vote down vote up
@Test
public void testTwoClustersBroadcast() {
	DirectedWeightedPseudograph<Integer, DefaultWeightedEdge> graph = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);
	
	graph.addVertex(1);
	graph.addVertex(2);
	graph.addVertex(3);
	
	graph.addVertex(4);
	graph.addVertex(5);
	graph.addVertex(6);
	
	/**
	 * Imagine two groups, 1,2,3 and 4,5,6, each internally connected via wifi, but 1,2, and 5 have internet access in addition.
	 * */
	addSymmetricEdge(graph, 1, 2, 1);
	addSymmetricEdge(graph, 2, 3, 2);
	addSymmetricEdge(graph, 3, 1, 1);
	
	addSymmetricEdge(graph, 4, 5, 1);
	addSymmetricEdge(graph, 5, 6, 1);
	addSymmetricEdge(graph, 6, 4, 2);
	
	addSymmetricEdge(graph, 1, 5, 10);
	addSymmetricEdge(graph, 2, 5, 11);
	
	Tree<Integer> tree = MinimumSteinerTreeApproximation.approximateSteinerTree(graph, 1, new HashSet<>(Arrays.asList(1,2,3,4,5,6)));

	Tree<Integer> expectedResult =
		new Tree<>(1, 
			new Tree<>(2),
			new Tree<>(3),
			new Tree<>(5,
				new Tree<>(4), 
				new Tree<>(6)
			)
		);
	
	assertTrue("Did not get expected result.", tree.equals(expectedResult));
}
 
Example #30
Source File: Matching.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a new column (matching)
 * @param creator who created the matching
 * @param isArtificial indicates whether its an artificial column
 * @param associatedPricingProblem pricing problem for which the matching is created
 * @param edges edges in the matching
 * @param succ successor array
 * @param cost cost of matching (sum of edge lengths)
 */
public Matching(String creator, boolean isArtificial,	PricingProblemByColor associatedPricingProblem,
		Set<DefaultWeightedEdge> edges,
		int[] succ,
		int cost) {
	super(associatedPricingProblem, isArtificial, creator);
	this.edges=edges;
	this.succ=succ;
	this.cost=cost;
}