Skip to content
Snippets Groups Projects
Commit 6778ca96 authored by Paul A. Rubin's avatar Paul A. Rubin
Browse files

Added pairwise swapping heuristic.

parent 6c84ceb9
No related branches found
No related tags found
No related merge requests found
package solvers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import xmtrclusters.Problem;
/**
* PairSwap implements a heuristic that swaps pairs of transmitters to
* improve a solution.
*
* @author Paul A. Rubin (rubin@msu.edu)
*/
public final class PairSwap {
private final List<Collection<Integer>> clusters; // list of clusters
/**
* Constructs the heuristic instance and solves it.
* @param prob the problem to solve
* @param initial the initial clustering
* @param timeLimit run time limit (ms.)
*/
public PairSwap(final Problem prob,
final Collection<Collection<Integer>> initial,
final long timeLimit) {
long start = System.currentTimeMillis();
long endBy = start + timeLimit;
int nSwaps = 0; // counts swaps done
int nT = prob.getNTrans();
int nC = initial.size();
// Copy the initial clustering.
clusters = new ArrayList<>(initial);
// Record the total service quality in each cluster and which cluster
// holds each transmitter.
int[] owner = new int[nT];
double[] value = new double[nC];
for (int c = 0; c < nC; c++) {
value[c] = prob.clusterQuality(clusters.get(c));
for (int t : clusters.get(c)) {
owner[t] = c;
}
}
// Loop until time runs out or no further swaps occur.
boolean loop = true;
while (loop && System.currentTimeMillis() < endBy) {
// Iterate over every pair of transmitters.
loop = false;
for (int t = 0; t < nT; t++) {
int i = owner[t];
double u = value[i];
for (int t1 = t + 1; t1 < nT; t1++) {
int i1 = owner[t1];
double u1 = value[i1];
// Test the clusters modified by the swap.
HashSet<Integer> c = new HashSet<>(clusters.get(i));
HashSet<Integer> c1 = new HashSet<>(clusters.get(i1));
c.remove(t);
c.add(t1);
c1.remove(t1);
c1.add(t);
double v = prob.clusterQuality(c);
double v1 = prob.clusterQuality(c1);
// If the swap is beneficial, do it.
if (v + v1 > u + u1) {
clusters.set(i, c);
clusters.set(i1, c1);
owner[t] = i1;
owner[t1] = i;
value[i] = v;
value[i1] = v1;
i = i1;
u = v;
nSwaps += 1;
loop = true;
}
}
}
}
long time = System.currentTimeMillis() - start;
System.out.println("\nSwap heuristic did " + nSwaps + " swaps in "
+ time + " ms.");
}
/**
* Gets the final result of the heuristic.
* @return the collection of clusters found
*/
public Collection<Collection<Integer>> getSolution() {
return Collections.unmodifiableCollection(clusters);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment